Call method by string?
1 2 3 4 5 6 7 8 9 10 | Class MyClass{ private $data=array('action'=>'insert'); public function insert(){ echo 'called insert'; } public function run(){ $this->$this->data['action'](); } } |
这不管用:
1 | $this->$this->data['action'](); |
号
唯一可能的是使用
尝试:
1 | $this->{$this->data['action']}(); |
您可以通过首先检查它是否可以调用来安全地执行此操作:
1 2 3 4 5 6 | $action = $this->data['action']; if(is_callable(array($this, $action))){ $this->$action(); }else{ $this->default(); //or some kind of error message } |
号
再强调一下上面提到的,
1 2 3 4 |