Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using class name from a static constant statically in PHP

I have the class name Car stored as a static variable in constants. I would like to use this constant to call the function a. One options is to use an intermediate variable $tmp. I could then call $tmp::a(). Is there a way to do this in one statement? My attempt is below.

class Car{
    public static function a(){
        return 'hi';
    }
}

class Constants{
    public static $use='Car';
}

$tmp=Constants::$use;

echo(${Constants::$use}::a());

IDEOne link

Output is as follows

PHP Notice:  Undefined variable: Car in /home/mU9w5e/prog.php on line 15
PHP Fatal error:  Class name must be a valid object or a string in /home/mU9w5e/prog.php on line 15
like image 748
Casebash Avatar asked Dec 16 '22 10:12

Casebash


2 Answers

There is always call_user_func():

echo call_user_func( array( Constants::$use, 'a'));

IDEOne Demo

like image 105
nickb Avatar answered Dec 28 '22 07:12

nickb


The only alternative that I could find to @nickb's way was using something I've never heard of, but hey that's what SO is for!

I found the ReflectionMethod, which seems to be more bloated than the call_user_func, but was the only alternative way that I could find:

<?php
class Car{
    public static function a(){
        return 'hi';
    }
}

class Constants{
    public static $use='Car';
}
$reflectionMethod = new ReflectionMethod(Constants::$use, 'a');
echo $reflectionMethod->invoke(new Car());

The above is a bit of a failed experiment as Casebash doesn't want to create temp variables.

As CORRUPT mentioned in the comments, it is possible to use the following although was tested on PHP version 5.4.14 (which I am unable to do):

echo (new ReflectionMethod(Constants::$use, 'a'))->invoke(new Car());
like image 45
Samuel Cook Avatar answered Dec 28 '22 07:12

Samuel Cook