Home » Php » php – Call method by string?

php – Call method by string?

Posted by: admin April 23, 2020 Leave a comment

Questions:
Class MyClass{
  private $data=array('action'=>'insert');
  public function insert(){
    echo 'called insert';
  }

  public function run(){
    $this->$this->data['action']();
  }
}

This doens’t work:

$this->$this->data['action']();

only possibilites is to use call_user_func(); ?

How to&Answers:

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
}

Answer:

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