问题描述
是否可以在ReflectionMethod::invokeArgs
中将参数作为关联数组传递?这将允许我以与声明的顺序不同的顺序传递参数.
Is it possible to pass parameters as an associative array in ReflectionMethod::invokeArgs
? This would allow me to pass the arguments in a different order than declared.
例如:
class A
{
public function someMethod($a, $b)
{
return sprintf("a - %s, b - %s", $a, $b);
}
}
$rm = new ReflectionMethod('A', 'someMethod');
echo $rm->invokeArgs(new A(), array('b' => 1, 'a' => 2));
推荐答案
您可以通过覆盖invokeArgs
方法并实现所需的功能来实现此目的(在您的情况下,您似乎要使用命名参数):
You can do this by overwriting the invokeArgs
method and implementing the functionality you need (in your case it looks like you want to use named arguments):
class ReflectionMethodA extends ReflectionMethod
{
public function invokeArgs($object, Array $args = array())
{
$parameters = $this->getParameters();
foreach($parameters as &$param)
{
$name = $param->getName();
$param = isset($args[$name]) ? $args[$name] : $param->getDefaultValue();
}
unset($param);
return parent::invokeArgs($object, $parameters);
}
}
$rm = new ReflectionMethodA('A', 'someMethod');
echo $rm->invokeArgs(new A(), array('b' => 1, 'a' => 2));
输出:
a - 2, b - 1
编辑:以下类是改进的(支持命名和编号的参数以及通过引用传递)和更灵活的变体(用于任何回调),将任何有效的回调作为构造函数中的参数.
An improved (supporting both named and numbered arguments as well as passing by reference) and more flexible variant (to be used for any callback) is the following class, taking any valid callback as parameter in it's constructor.
用法:
$rc = new ReflectedCallback(array(new A(), 'someMethod'));
echo $rc->invokeArgs(array('b' => 1, 'a' => 2));
这篇关于我可以将关联数组作为参数传递给ReflectionMethod :: invokeArgs吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!