Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php call static method of class which is in variable

I have a namespace App\Term which is saved as a property: $this->name = 'App\Term'. How can I call a static method of this class like $this->name::methodName() ? Or is there another solution for this problem?

like image 854
FreeLightman Avatar asked Oct 22 '15 19:10

FreeLightman


People also ask

How can I access private static method in PHP?

Static properties are accessed using the Scope Resolution Operator ( :: ) and cannot be accessed through the object operator ( -> ). It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self , parent and static ).

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

How do you call a non-static method from a 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.

Can I call a static method inside a regular one?

@Ian Dunn Put simply, $this only exists if an object has been instantiated and you can only use $this->method from within an existing object. If you have no object but just call a static method and in that method you want to call another static method in the same class, you have to use self:: .


1 Answers

You can use call_user_func for this.

call_user_func($name.'::methodName');

Or:

call_user_func(array($name, 'methodName'));
like image 56
Rocket Hazmat Avatar answered Oct 19 '22 23:10

Rocket Hazmat