Search code examples
phpdynamicmethodscall

php multiple dynamic calls


I know it's possible to call one method dynamically like

$function = 'foo';
$bar = new Bar();
$bar->$function();

What I'm trying to achieve is multiple call, like I receive an unknown amount of method ordered, and i have to call them from one object. I get for example 'foo', 'bar', 'bro', and I have to do dynamically $object->foo()->bar()->bro().

Is it possible ? I know the call_user_func but I dont think it can solve this problem... Thanks a lot !


Solution

  • You can loop over the functions and apply them to each result:

    $arr = array('foo','bar','bro');
    $object = getTheObject();
    $res = $object;
    foreach($arr as $funcName){
        $res = $res->$funcName();
    }
    

    However this kind of code gives people nightmares since it's really not very clear what is going on. Consider using other approaches to do what you need.