We can do black magic, which is useful in templating block calls:
<?php
$object->__named('methodNameHere', array('arg3' => 'three', 'arg1' => 'one'));
...
/**
* Pass method arguments 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->getParameters() as $param)
{
/* @var $param ReflectionParameter */
if(isset($args[$param->getName()]))
{
$pass[] = $args[$param->getName()];
}
else
{
$pass[] = $param->getDefaultValue();
}
}
return $reflection->invokeArgs($this, $pass);
}
?>ReflectionMethod::invokeArgs
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
ReflectionMethod::invokeArgs
Референца за `reflectionmethod.invokeargs.php` со подобрена типографија и навигација.
ReflectionMethod::invokeArgs
(PHP 5 >= 5.1.2, PHP 7, PHP 8)
ReflectionMethod::invokeArgs — Повикај аргументи
= NULL
Го повикува рефлектираниот метод и ги поминува неговите аргументи како низа.
Параметри
Вратени вредности
Враќа резултат од методот.
Errors/Exceptions
А ReflectionException ако object
параметарот не содржи инстанца на класата во која е деклариран овој метод.
А ReflectionException ако повикувањето на методот не успеа.
Дневник на промени
| Верзија | = NULL |
|---|---|
| 8.0.0 |
args клучевите сега ќе се толкуваат како имиња на параметри, наместо да се игнорираат тивко.
|
Примери
Пример #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'));
?>Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред
Hello Mike
Белешки
Забелешка:
Ако функцијата има аргументи што треба да бидат референци, тогаш тие мора да бидат референци во предадената листа на аргументи.
Види Исто така
- Овозможува повикување на заштитен или приватен метод преку - Повикај
- __invoke()
- call_user_func_array() - Повикајте повик со низа од параметри
Белешки од корисници 4 белешки
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.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:
19Passing arguments by reference works:
<?php $rm->invokeArgs($object, array(&$foo, $bar)); ?>