Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call static method from a string name in 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();

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

like image 554
Sergi Juanola Avatar asked Jul 10 '12 10:07

Sergi Juanola


People also ask

How can I call static method from static method in PHP?

Example Explained Here, we declare a static method: welcome(). Then, we call the static method by using the class name, double colon (::), and the method name (without creating an instance of the class first).

How static method is invoked in PHP?

To add a static method to the class, static keyword is used. They can be invoked directly outside the class by using scope resolution operator (::) as follows: MyClass::test();

Can static method be called by object PHP?

The static method can call without object while instance method can not be called without object.

How can call non-static method from static method in PHP?

In PHP 7, calling non-static methods statically is deprecated, and will generate an E_DEPRECATED warning. See Static methods (php.net) for details. In the following example, the method foo() is called as dynamic while actually it is static.


1 Answers

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();
like image 72
Jon Avatar answered Sep 23 '22 03:09

Jon