Using a class name from a static constant statically in PHP

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

 class Car{ public static function a(){ return 'hi'; } } class Constants{ public static $use='Car'; } $tmp=Constants::$use; echo(${Constants::$use}::a()); 

IDEOne link

The 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 
+4
source share
3 answers

There is always call_user_func() :

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

IDEOne Demo

+7
source

The only alternative I could find on @nickb is something that I have never heard of, but hey, this is for SO!

I found ReflectionMethod , which seems more bloated than call_user_func , but was the only alternative way I can 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 result is an unsuccessful experiment because Casebash does not want to create temporary variables.

As CORRUPT mentioned in the comments, the following can be used, although it has been tested with PHP version 5.4.14 (which I cannot do):

 echo (new ReflectionMethod(Constants::$use, 'a'))->invoke(new Car()); 
+3
source

I have a crazy solution, but you should never use it: ^)

 echo ${${Constants::$use} = Constants::$use}::a(); 
+2
source

Source: https://habr.com/ru/post/1481291/


All Articles