php 通过字符串调用方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5451394/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call method by string?
提问by dynamic
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();
?
唯一的可能是使用call_user_func();
?
回答by Mārti?? Briedis
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
}
回答by Brad Koch
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.
重新强调了OP提到什么,call_user_func()
和call_user_func_array()
也是不错的选择。特别是,call_user_func_array()
当每个函数的参数列表可能不同时,在传递参数方面做得更好。
call_user_func_array(
array($this, $this->data['action']),
$params
);