skirato skirato - 4 months ago 7
PHP Question

How to chain call functions by using a string containing that chain in PHP

I have a chain call like so:


I know that I can use a string to call a function on an object:

$functionName = 'getUser';
$object->$functionName() or call_user_func(array($object, functionName))

I was wondering if it was possible to do the same for a chain call?
I tried to do:

$functionName = 'getUser()->getName';

But I get an error

Method name must be a string

I guess this is because the
cannot be interpreted since they are part of a string? Is there any way I can achieve this without having to do:

$function1 = getUser;
$function2 = getName;

The aim is to get an array of functions and to chain them, in order to call this chain on the given object, e.g.:

$functions = array('getCoordinates', 'getLongitude'); // or any other chain call
$functionNames = implode('()->',$functions);


Let's start with a more neutral text format that's easy to handle:

$chain = 'getUser.getName';

And then simply reduce it:

$result = array_reduce(explode('.', $chain), function ($obj, $method) {
    return $obj->$method();
}, $object);

Note that you could even inspect the $obj to figure out whether $method is a method or a property or even an array index and return the value appropriately. See Twig for inspiration.