Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
like image 380
openfrog Avatar asked Oct 16 '25 11:10

openfrog


1 Answers

$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.

like image 199
Matchu Avatar answered Oct 18 '25 01:10

Matchu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!