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?
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 ).
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();
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.
@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:: .
You can use call_user_func
for this.
call_user_func($name.'::methodName');
Or:
call_user_func(array($name, 'methodName'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With