问题描述
我需要调用一个类的静态方法,但我只有一个类名,没有它的实例.我就是这样做的.
I need to call a static method of a class, but I only have a classname, not an instance of it. I am doing it this way.
$class = new "ModelName";
$items = $class::model()->findAll();
它在我的电脑上工作,但是当我移动到服务器时,它抛出一个意外的 T_PAAMAYIM_NEKUDOTAYIM
,所以我认为它实际上希望模型是一个变量而不是一个方法.
It works on my computer, but when I move to the server, it throws an unexpected T_PAAMAYIM_NEKUDOTAYIM
, so I think it actually expects model to be a variable instead of a method.
PS:如果有帮助,那就是 Yii 框架,所以如果有另一种调用 find() 函数的方法,对我来说没问题.
PS: If it helps, it's Yii framework, so if there's another way to call the find() functions, it's ok to me.
提前致谢
推荐答案
这是因为您的服务器运行的 PHP 版本早于 5.3.0,不支持此语法.
This is because your server runs a version of PHP earlier than 5.3.0, in which this syntax is not supported.
来自关于范围解析运算符的文档:
从 PHP 5.3.0 开始,可以使用多变的.变量的值不能是关键字(例如 self、parent和静态).
无论如何,您始终可以使用 call_user_func代码>
:
In any case, you can always use call_user_func
:
$class = "ModelName"; // the "new" in your example was a typo, right?
$items = call_user_func(array($class, 'model'))->findAll();
这篇关于从 PHP 中的字符串名称调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!