4

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
4

3 回答 3

7

总是有call_user_func()

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

IDEOne 演示

于 2013-05-17T02:31:08.650 回答
3

我可以找到@nickb方式的唯一替代方法是使用我从未听说过的东西,但是嘿,这就是 SO 的用途!

我找到了ReflectionMethod,它似乎比 更臃肿call_user_func,但这是我能找到的唯一替代方法:

<?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());

以上是一个失败的实验,因为Casebash不想创建临时变量。

正如评论中提到的损坏,尽管已经过测试PHP version 5.4.14(我无法做到),但可以使用以下内容:

echo (new ReflectionMethod(Constants::$use, 'a'))->invoke(new Car());
于 2013-05-17T02:49:53.687 回答
2

我有疯狂的解决方案,但你永远不应该使用它:^)

echo ${${Constants::$use} = Constants::$use}::a();
于 2013-05-17T03:12:54.953 回答