dynamic class method call chaining by array values

php

Solution

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);
}

Problem

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!

Original source