©
Dieses Dokument verwendet PHP-Handbuch für chinesische Websites Freigeben
(PHP 5 >= 5.1.0)
ReflectionMethod::invokeArgs — 带参数执行
$object
, array $args
)使用数组给方法传送参数,并执行他。
object
调用方法的对象,如果是静态对象,设置为 null
args
使用 array 传送的方法参数。
返回方法返回值
如果 object
指定的实例无法执行方法,那么产生
ReflectionException 异常。
如果方法调用失败,产生 ReflectionException
Example #1 ReflectionMethod::invokeArgs() example
<?php
class HelloWorld {
public function sayHelloTo ( $name ) {
return 'Hello ' . $name ;
}
}
$reflectionMethod = new ReflectionMethod ( 'HelloWorld' , 'sayHelloTo' );
echo $reflectionMethod -> invokeArgs (new HelloWorld (), array( 'Mike' ));
?>
以上例程会输出:
Hello Mike
Note:
如果函数有参数需为引用,那么它们必须以引用方式传入。
[#1] CodeCoutureXX at gmail dot com [2015-09-03 21:12:17]
If you need to call ReflectionMethod::invokeArgs() on a static function you can pass NULL in for the $object parameter.
Example:
<?php
class myClass {
public static myStaticFunc($a, $b) {
return $a + $b;
}
}
$ref = new ReflectionMethod('myClass', 'myStaticFunc');
echo $ref->invokeArgs(NULL, [12, 7]);
?>
produces the following output:
19
[#2] cweiske at cweiske dot de [2011-03-25 07:34:21]
Passing arguments by reference works:
<?php $rm->invokeArgs($object, array(&$foo, $bar)); ?>
[#3] agent_harris at secure-mail dot biz [2011-02-13 07:12:03]
There is a simple workaround for the reference passing problem:
Since the reflection api has to handle all parameters in a generic way it has no chance to guess if you wish to pass data per value or reference.
But it seems that you can also decide to pass a reference from where you call the function or method (not just only by the ampersand prefix in its declaration).
So just do the following; which worked for me:
<?php
//...
$method->invoke($object, $inputValue, &$outputValue);
?>
Since this will only be necessary with arrays and primitive data types it should be acceptable in most cases to know in advance if you need to pass per reference. But it is probably although necessary to keep the ampersand always in the declaration (because of the at least two layers between the actual function and your invoke call).
If this is the expected behavior it will maybe make sense to mention it in the documentation for invoke and invokeArgs.
[#4] serg dot smertin at gmail dot com [2010-09-21 06:51:09]
We can do black magic, which is useful in templating block calls:
<?php
$object->__named('methodNameHere', array('arg3' => 'three', 'arg1' => 'one'));
...
public function __named($method, array $args = array())
{
$reflection = new ReflectionMethod($this, $method);
$pass = array();
foreach($reflection->getParameters() as $param)
{
if(isset($args[$param->getName()]))
{
$pass[] = $args[$param->getName()];
}
else
{
$pass[] = $param->getDefaultValue();
}
}
return $reflection->invokeArgs($this, $pass);
}
?>