如何通过使用PHP中包含该链的字符串来链接调用函数 [英] How to chain call functions by using a string containing that chain in PHP
问题描述
我有一个像这样的链式呼叫:
I have a chain call like so:
$object->getUser()->getName();
我知道我可以使用字符串来调用对象上的函数:
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';
$object->functionName();
但是我遇到了错误
方法名称必须是字符串
Method name must be a string
我想这是因为()
和->
无法解释,因为它们是字符串的一部分?有什么方法可以不用做而做到:
I guess this is because the ()
and ->
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;
$object->$function1()->$function2();
目的是获得一系列函数并将其链接起来,以便在该链上调用给定的对象,例如:
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);
$object->$functionNames()
推荐答案
让我们从一个易于处理的中性文本格式开始:
Let's start with a more neutral text format that's easy to handle:
$chain = 'getUser.getName';
然后简单地 reduce 它:
$result = array_reduce(explode('.', $chain), function ($obj, $method) {
return $obj->$method();
}, $object);
请注意,您甚至可以检查 $ obj
确定 $ method
是方法还是属性,甚至是数组索引,然后 return
是适当的值。请参见嫩枝以获取灵感。
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.
这篇关于如何通过使用PHP中包含该链的字符串来链接调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!