accessing static methods using a variable class name (PHP)

ぃ、小莉子 提交于 2019-12-22 03:18:09

问题


I am trying to access a static method, but using a variable as the class name. Is this possible? I seem to be having issues with it. I want to be able to do something like this:

class foo {
    public static function bar() {
        echo 'test';
    }
}

$variable_class_name = 'foo';
$variable_class_name::bar();

And I want to be able to do similar using static variables as well.


回答1:


That syntax is only supported in PHP 5.3 and later. Previous versions don't understand that syntax, hence your parse error (T_PAAMAYIM_NEKUDOTAYIM refers to the :: operator).

In previous versions you can try call_user_func(), passing it an array containing the class name and its method name:

$variable_class_name = 'foo';
call_user_func(array($variable_class_name, 'bar'));



回答2:


You can use reflection for PHP 5.1 and above:

class foo {
    public static $bar = 'foobar';
}

$class = 'foo';
$reflector = new ReflectionClass($class);
echo $reflector->getStaticPropertyValue('bar');

> foobar


来源:https://stackoverflow.com/questions/5059957/accessing-static-methods-using-a-variable-class-name-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!