开发者

How to create an instance of an class and call a method on it, in this case?

开发者 https://www.devze.com 2022-12-15 02:46 出处:网络
Problem: I need to dynamically call a class and a method of that class. The only thing I get is two 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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消