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条回答 默认 最新

  • duanfazhun0383 2013-08-20 14:35
    关注

    You're looking for call_user_func_array():

    foreach($tests as $test=>$parameters) {
        call_user_func_array( array( $this, $test), $parameters);
    }
    

    Loading this into a simple test class:

    class Test {
        public function setUp() {
            $tests = array(
                'printHello'    =>  array(),    
                'printWorld'    =>  array(),
                'printName' =>  array('Bob'),
            );
            foreach( $tests as $fn => $params) 
                call_user_func_array( array( $this, $fn), $params);
        }
    
        public function printHello() {
            echo "Hello, ";
        }
    
        public function printWorld() {
            echo "World!";
        }
    
        public function printName($name=false) {
            echo $name;
        }
    }
    

    We can see that this outputs for PHP >= 5.0.0:

    Hello, World!Bob
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)