使用变量类名(PHP)访问静态方法 [英] accessing static methods using a variable class name (PHP)
问题描述
我正在尝试访问静态方法,但使用变量作为类名.这可能吗?我似乎对此有疑问.我希望能够做这样的事情:
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.
推荐答案
该语法仅在PHP 5.3和更高版本中受支持.以前的版本不了解该语法,因此会出现解析错误(T_PAAMAYIM_NEKUDOTAYIM
指的是::
运算符).
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).
在以前的版本中,您可以尝试call_user_func()
,将包含类名及其方法名的数组传递给它:
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'));
这篇关于使用变量类名(PHP)访问静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!