Php 通过字符串调用方法?
这不起作用:Php 通过字符串调用方法?,php,oop,Php,Oop,这不起作用: Class MyClass{ private $data=array('action'=>'insert'); public function insert(){ echo 'called insert'; } public function run(){ $this->$this->data['action'](); } } 唯一的可能性是使用call_user_func()?尝试: $this->$this->
Class MyClass{
private $data=array('action'=>'insert');
public function insert(){
echo 'called insert';
}
public function run(){
$this->$this->data['action']();
}
}
唯一的可能性是使用call_user_func()代码>?尝试:
$this->$this->data['action']();
通过先检查它是否可调用,您可以安全地执行此操作:
$this->{$this->data['action']}();
再次强调OP提到的内容,也是很好的选择。特别是,call\u user\u func\u array()
在传递参数方面做得更好,因为每个函数的参数列表可能不同
$action = $this->data['action'];
if(is_callable(array($this, $action))){
$this->$action();
}else{
$this->default(); //or some kind of error message
}
确保检查函数是否存在:首先检查函数_exists()!它起作用了。我是否应该使用任何安全技巧,如function exists或functions allowed array?@MarekBar如果输入来自用户,则应始终正确转义。理想情况下,使用带有允许操作的白名单。@JesseBunch如果您使用allready检查is_Callable,则不需要使用function_exist。值得一提的是,在某些版本的PHP中,is_callable不尊重可视性,
call_user_func_array(
array($this, $this->data['action']),
$params
);