How to create an instance of an class and call a method on it, in this case?
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 i开发者_如何学编程nstance specified in $method?
Like:
$instance = new MyClass;
$instance->myMethod();
$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.
精彩评论