Note: If you want to invoke protected or private methods, you'll first have to make them accessible using the setAccessible() method (see http://php.net/reflectionmethod.setaccessible ).
PHP - Manual: ReflectionMethod::invoke
2024-11-15
(PHP 5, PHP 7, PHP 8)
ReflectionMethod::invoke — Invoke
执行一个反射的方法。
object
如果执行的方法是静态类,那么这个参数传送 null。
parameter
0,或者传送给方法的参数列表。可以通过这个参数,给方法传送大量的参数。
返回方法的返回值
示例 #1 ReflectionMethod::invoke() example
<?php
class HelloWorld {
public function sayHelloTo($name) {
return 'Hello ' . $name;
}
}
$reflectionMethod = new ReflectionMethod('HelloWorld', 'sayHelloTo');
echo $reflectionMethod->invoke(new HelloWorld(), 'Mike');
?>
以上例程会输出:
Hello Mike
注意:
如果函数有参数需为引用,那么它们必须以引用方式传入。
Note: If you want to invoke protected or private methods, you'll first have to make them accessible using the setAccessible() method (see http://php.net/reflectionmethod.setaccessible ).
This method can be used to call a overwritten public method of a parent class on an child instance
The following code will output "A":
<?php
class A
{
public function foo()
{
return __CLASS__;
}
}
class B extends A
{
public function foo()
{
return __CLASS__;
}
}
$b = new B();
$reflection = new ReflectionObject($b);
$parentReflection = $reflection->getParentClass();
$parentFooReflection = $parentReflection->getMethod('foo');
$data = $parentFooReflection->invoke($b);
echo $data;
?>
Seems that Reflection doesn`t resolve late static bindings - var_dump will show "string 'a' (length=1)".
<?php
class ParentClass { protected static $a = 'a'; static public function init() { return static::$a; } }
class ChildClass extends ParentClass { protected static $a = 'b'; }
$r = new ReflectionClass('ChildClass');
var_dump($r->getMethod('init')->invoke(null));
?>
官方地址:https://www.php.net/manual/en/reflectionmethod.invoke.php