Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method by string?

Tags:

oop

php

People also ask

How do you call a method in a string?

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.

Can you use a string to call a function?

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.

How do you call a function inside a string in JavaScript?

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
);