Call method by string?

PhpOop

Php Problem Overview


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

Php Solutions


Solution 1 - Php

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
}

Solution 2 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondynamicView Question on Stackoverflow
Solution 1 - PhpMārtiņš BriedisView Answer on Stackoverflow
Solution 2 - PhpBrad KochView Answer on Stackoverflow