Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic static method call in PHP?

Please could someone experienced in PHP help out with the following. Somewhere in my code, I have a call to a public static method inside a non-instantiated class:

$result = myClassName::myFunctionName(); 

However, I would like to have many such classes and determine the correct class name on the fly according to the user's language. In other words, I have:

$language = 'EN'; 

... and I need to do something like:

$result = myClassName_EN::myFunctionName(); 

I know I could pass the language as a parameter to the function and deal with it inside just one common class but for various reasons, I would prefer a different solution.

Does this make any sense, anyone? Thanks.

like image 593
Tom Avatar asked Jan 21 '10 11:01

Tom


People also ask

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 we call static method with object 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 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.

Why it is called static method?

Static Method Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.


Video Answer


1 Answers

Use the call_user_func function:

http://php.net/manual/en/function.call-user-func.php

Example:

call_user_func('myClassName_' . $language . '::myFunctionName'); 
like image 179
Ben Everard Avatar answered Sep 22 '22 06:09

Ben Everard