phpclassmethodsdynamicinstantiation

Create an instance of a class and call a method on it via variables containing the class name and method name as strings


Problem: I need to dynamically call a class and a method of that class. The only thing I get is two strings:

$class = "MyClass";
$method = "myMethod";

How can I create an Instance of the class specified in $class and then call a method on that instance specified in $method?

Like:

$instance = new MyClass;
$instance->myMethod();

Solution

  • $instance = new $class;
    $instance->$method();
    

    Just like you'd expect. Obviously, though, if you're taking this as user input, you'll want to be 100% sure that you validate the class and method names against an acceptable list. If the class is only for public APIs, then you don't need a separate whitelist for methods, but you most definitely need to be 100% sure when you take that approach, since allowing direct user input into your program flow is very, very dangerous.