There are two methods to call a function from string stored in a variable. The first one is by using the window object method and the second one is by using eval() method. The eval() method is older and it is deprecated.
In summary, to call a function from a string, the functions getattr() , locals() , and globals() are used. getattr() will require you to know what object or module the function is located in, while locals() and globals() will locate the function within its own scope.
You just need convert your string to a pointer by window[<method name>] . example: var function_name = "string"; function_name = window[function_name];
Try:
$this->{$this->data['action']}();
You can do it safely by checking if it is callable first:
$action = $this->data['action'];
if(is_callable(array($this, $action))){
$this->$action();
}else{
$this->default(); //or some kind of error message
}
Reemphasizing what the OP mentioned, call_user_func()
and call_user_func_array()
are also good options. In particular, call_user_func_array()
does a better job at passing parameters when the list of parameters might be different for each function.
call_user_func_array(
array($this, $this->data['action']),
$params
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With