按字符串调用方法?

dyn*_*mic 45 php oop

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)

  • 一定要检查函数是否存在:首先是function_exists()! (4认同)
  • @MarekBar如果输入来自用户,您应该始终正确地转义它.理想情况下,使用允许操作的白名单. (3认同)

Bra*_*och 9

重新强调了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)