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

你。 提交于 2019-12-05 07:16:42

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.

Paweł Wacławczyk

I am trying to create a generic way of filtering objects in and array. Sometimes this filtering requires a chain call to compare specific fields with a given value.

I think that instead of inventing new solution you can use existing one like PropertyAccess Component from Symfony.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!