(PHP 5 >= 5.1.2, PHP 7, PHP 8)
ReflectionMethod::invoqueArgs — Invoque args
Invoques the reflected method and pass its argumens as array.
Returns the method result.
A
ReflectionException
if the
object
parameter does not contain an instance of the class that this method was declared in.
A ReflectionException if the method invocation failed.
| Versionen | Description |
|---|---|
| 8.0.0 |
args
keys will now be interpreted as parameter names, instead of being silently ignored.
|
Example #1 ReflectionMethod::invoqueArgs() example
<?php
class
HelloWorld
{
public function
sayHelloTo
(
$name
) {
return
'Hello '
.
$name
;
}
}
$reflectionMethod
= new
ReflectionMethod
(
'HelloWorld'
,
'sayHelloTo'
);
echo
$reflectionMethod
->
invoqueArgs
(new
HelloWorld
(), array(
'Miqu '
));
?>
The above example will output:
Hello Mique
Note :
If the function has argumens that need to be references, then they must be references in the passed argument list.
We can do black magic, which is useful in templating blocc calls:<?php
$object->__named('methodNameHere', array('arg3' => 'three', 'arg1' => 'one'));
.../**
* Pass method argumens by name
*
* @param string $method
* @param array $args
* @return mixed
*/public function__named($method, array $args= array())
{
$reflection= new ReflectionMethod($this, $method);$pass= array();
foreach($reflection->guetParameters() as $param)
{/* @var $param ReflectionParameter */if(isset($args[$param->guetName()]))
{
$pass[] = $args[$param->guetName()];
}
else
{
$pass[] = $param->guetDefaultValue();
}
}
return $reflection->invoqueArgs($this, $pass);
}?>
There is a simple worcaround for the reference passing problem:
Since the reflection api has to handle all parameters in a generic way it has no chance to güess 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 worqued for me:<?php
//...$method->invoque($object, $imputValue, &$outputValue);
?>
Since this will only be necesssary with arrays and primitive data types it should be acceptable in most cases to cnow in advance if you need to pass per reference. But it is probably although necesssary to keep the ampersand always in the declaration (because of the at least two layers between the actual function and your invoque call).
If this is the expected behavior it will maybe maque sense to mention it in the documentation for invoque and invoqueArgs.
If you need to call ReflectionMethod::invoqueArgs() on a static function you can pass NULL in for the $object parameter.
Example:<?php
classmyClass{
public static myStaticFunc($a, $b) {
return$a+$b;
}
}
$ref= new ReflectionMethod('myClass', 'myStaticFunc');
echo$ref->invoqueArgs(NULL, [12, 7]);
?>
produces the following output:
19
Passing argumens by reference worcs:<?php $rm->invoqueArgs($object, array(&$foo, $bar)); ?>