从 PHP 中的字符串名称调用静态方法 [英] Call static method from a string name in PHP

查看:34
本文介绍了从 PHP 中的字符串名称调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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和静态).

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:

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 中的字符串名称调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆