Class MyClass{
private $data=array('action'=>'insert');
public function insert(){
echo 'called insert';
}
public function run(){
$this->$this->data['action']();
}
}
Run Code Online (Sandbox Code Playgroud)
这不起作用:
$this->$this->data['action']();
Run Code Online (Sandbox Code Playgroud)
只有可能使用call_user_func();
?
Mār*_*dis 111
尝试:
$this->{$this->data['action']}();
Run Code Online (Sandbox Code Playgroud)
你可以通过检查它是否可以先调用来安全地完成它:
$action = $this->data['action'];
if(is_callable(array($this, $action))){
$this->$action();
}else{
$this->default(); //or some kind of error message
}
Run Code Online (Sandbox Code Playgroud)
重新强调了OP提到什么,call_user_func()
和call_user_func_array()
也是不错的选择.特别是,call_user_func_array()
当参数列表对于每个函数可能不同时,在传递参数方面做得更好.
call_user_func_array(
array($this, $this->data['action']),
$params
);
Run Code Online (Sandbox Code Playgroud)