Is there a way to call Static Classes / Methods by name?
Example:
$name = 'StaticClass';
($name)::foo();
I have classes which I keep all static methods in and I'd like to call them this way.
The static keyword is used to declare properties and methods of a class as static. Static properties and methods can be used without creating an instance of the class. The static keyword is also used to declare variables in a function which keep their value after the function has ended.
Introduction: A static class in PHP is a type of class which is instantiated only once in a program. It must contain a static member (variable) or a static member function (method) or both. The variables and methods are accessed without the creation of an object, using the scope resolution operator(::).
In PHP, if a static attribute is defined in the parent class, it cannot be overridden in a child class.
Solution 1. A static method provides NO reference to an instance of its class (it is a class method) hence, no, you cannot call a non-static method inside a static one.
$name::foo()
is possible since PHP5.3. In earlier versions you have to use
call_user_func(array($classname,$methodname))
You can do something like this using the call_user_func function
it would look something like the following
$name = 'staticClass';
call_user_func(array($name, 'foo'));
Hope this helps
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