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);
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题