dongqia3502 2012-11-26 19:30 采纳率: 100%
浏览 23
已采纳

动态类方法按数组值调用链接

For example I have class MyClass:

Class MyClass {

    public function method_1() {
        return $this;
    }

    public function method_2() {
        return $this;
    }

    public function method_n() {
        return $this;
    }
}

And I have array of functions and their arguments:

$array = array(
    'method_1' => array(
        '0' => 'first_argument',
        '1' => 'second_argument',
        '2' => 'nth_argument',
    ),
    'method_2' => array(
        '0' => 'first_argument',
        '1' => 'second_argument',
        '2' => 'nth_argument',
    ),
);

How to call MyClass methods from the array in chain?

$result = $my_class->$array['method_1']($array['method_1'][0], $array['method_1'][0])
    ->$array['method_1']($array['method_2'][0], $array['method_2'][0])
    ->$array['method_n']($array['method_n'][0], $array['method_n'][0]);

For example:

foreach($array as $function => $args) {
   // build chain here and execute after foreach
}

So, main question is how to call unlimited and unknown number of class functions with arguments in chain? Thanks!

  • 写回答

1条回答 默认 最新

  • dpps0715 2012-11-26 19:38
    关注

    Put your $array['method_*'] into {} brackets:

    $result = $my_class->{$array['method_1']}($array['method_1'][0], $array['method_1'][0])
        ->{$array['method_1']}($array['method_2'][0], $array['method_2'][0])
        ->{$array['method_n']}($array['method_n'][0], $array['method_n'][0]);
    

    If I may notice, although PHP allows this, for code readability and reliability you should rethink about dynamic chain calls. It may save you few lines, but may raise some headaches later debugging

    // Appendix: IMO, better way of doing your logic is via foreach and call_user_func_array():

    foreach ($array as $method => $args) {
        call_user_func_array(array($my_class, $method), $args);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记