通过字符串调用方法? [英] Call method by string?

查看:68
本文介绍了通过字符串调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Class MyClass{
  private $data=array('action'=>'insert');
  public function insert(){
    echo 'called insert';
  }

  public function run(){
    $this->$this->data['action']();
  }
}

这不起作用:

$this->$this->data['action']();

仅可能使用call_user_func();吗?

推荐答案

尝试:

$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
}

这篇关于通过字符串调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆