Home > database >  How to get class by name in PHP? [duplicate]
How to get class by name in PHP? [duplicate]

Time:09-27

I have the string with class name. I want to get a class with this name and call a static methods of this class.

How to make something like this?


$className = "Model";
getClassByName($className)::sayHello();

CodePudding user response:

You can simply call the method on the variable, you might want to wrap an "if" around it to check if the class exists.

$className = "Model";
if (class_exists($className)) {
    $className::sayHello();
}

You can check out this 3v4l for a repro case.

  •  Tags:  
  • php
  • Related