doucan9079 2013-08-20 14:32
浏览 44
已采纳

PHP - 从数组调用函数?

This is what I currently have:

public function setUp() {
    $tests = array(
                'printHello'    =>  array(),    
                'printWorld'    =>  array(),
                'printName' =>  array('Bob'),
            );
}


public function printHello() {
echo "Hello, ";
}

public function printWorld() {
echo "World!";
}

public function printName($name=false) {
echo $name;
}

What I want to do is loop through all the functions and run them consecutively. This is what I had to end up doing, but it just seems like there should be a more efficient way to do this:

foreach($tests as $test=>$parameters) {
    $num_params = count($parameters);
    switch($num_params) {
        case 0:
            $this->$test();
            break;
        case 1:
            $this->$test($parameters[0]);
            break;
        case 2:
            $this->$test($parameters[0],$parameters[1]);
            break;
        case 3:
            $this->$test($parameters[0],$parameters[1],$parameters[2]);
            break;
        default:
            echo "Error! More than 3 parameters for function" . $test . "!";
            exit;
    }       
}

I am using PHP 5.3. Is there a more efficient way to call the functions in a loop?

EDIT: I can't use call_user_func_array because I'm calling non-static methods from within their parent class. Is there another way?

  • 写回答

2条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 layui upload.render 问题 有偿
      • ¥15 “with “is not allowed in strict mode
      • ¥15 ADS2020使用村田数据库仿真出错
      • ¥15 如何解决爬取网站不定时不返回数据
      • ¥20 有几个关于fpga的基础问题黑盒仿真,建立保持时间,和仿真覆盖理论。
      • ¥20 如何在NCBI上下载高通量的测序数据
      • ¥15 L型TFET的器件参数
      • ¥15 nacos启动失败,文件夹权限
      • ¥20 vb6.0窗体中的vscroll控件无法响应鼠标滚轮事件,请教方法
      • ¥15 如何在linux服务器做视频静态资源访问接口