Call static method from a string name in PHP

天大地大妈咪最大 提交于 2020-01-02 00:55:10

问题


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();

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: If it helps, it's Yii framework, so if there's another way to call the find() functions, it's ok to me.

Thanks in advance


回答1:


This is because your server runs a version of PHP earlier than 5.3.0, in which this syntax is not supported.

From the documentation on the 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).

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();


来源:https://stackoverflow.com/questions/11410932/call-static-method-from-a-string-name-in-php

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