简体   繁体   English

在PHP中静态使用静态常量中的类名

[英]Using class name from a static constant statically in PHP

I have the class name Car stored as a static variable in constants. 我将类名Car存储为常量中的静态变量。 I would like to use this constant to call the function a . 我想用这个常量来调用函数a One options is to use an intermediate variable $tmp . 一种选择是使用中间变量$tmp I could then call $tmp::a() . 然后我可以调用$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 IDEOne链接

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() : 总是有call_user_func()

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

IDEOne Demo IDEOne演示

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! 我能找到@nickb的唯一方法是使用我从未听说过的东西,但是嘿,这就是SO的用途!

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: 我找到了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());

The above is a bit of a failed experiment as Casebash doesn't want to create temp variables. 以上是一个失败的实验,因为Casebash不想创建临时变量。

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): 正如评论中提到的CORRUPT ,虽然在PHP version 5.4.14 (我无法做到)上进行了测试,但可以使用以下内容:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM