How to dynamically create a PHP class name on the fly?

How can you call static functions of a class without knowing its name in advance in PHP?

  • You can instantiate objects without knowing the class names in advance. Ex: <?php $a = "foo"; $b = new $a; //Works fine. ?> Is there a similar way to call static functions without knowing class names in advance

  • Answer:

    This works: <?php $a = "ClassName"; $a::staticMethod(); ?>

Scot Lawrie at Quora Visit the source

Was this solution helpful to you?

Other answers

If you have an instance object of the class an question it can called it as a non static function works. <?php class Base { static function hello() { print("base_hello\n"); } } class Derived extends Base { static function hello() { print("derived_hello\n"); } } $instance = new Base(); $instance->hello(); $instance = new Derived(); $instance->hello(); ?> The output of the above is: base_hello derived_hello

Kartik Ayyar

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.