findAll(-6ren">
gpt4 book ai didi

php - 从 PHP 中的字符串名称调用静态方法

转载 作者:IT王子 更新时间:2023-10-29 00:11:54 24 4
gpt4 key购买 nike

我需要调用一个类的静态方法,但我只有一个类名,没有它的一个实例。我是这样做的。

$class = new "ModelName";
$items = $class::model()->findAll();

它在我的电脑上工作,但是当我移动到服务器时,它抛出一个意外的 T_PAAMAYIM_NEKUDOTAYIM,所以我认为它实际上期望模型是一个变量而不是一个方法。

PS:如果有帮助,那是 Yii 框架,所以如果有另一种调用 find() 函数的方法,对我来说没问题。

提前致谢

最佳答案

这是因为你的服务器运行的PHP版本早于5.3.0,不支持该语法。

来自 scope resolution operator 上的文档:

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

无论如何,你总是可以使用call_user_func :

$class = "ModelName"; // the "new" in your example was a typo, right?
$items = call_user_func(array($class, 'model'))->findAll();

关于php - 从 PHP 中的字符串名称调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11410932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com