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
There is always call_user_func()
:
echo call_user_func( array( Constants::$use, 'a'));
IDEOne Demo
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With