(PHP 5 >= 5.4.0, PHP 7, PHP 8)
ReflectionMethod::getClosure — Returns a dynamically created closure for the method
Create a closure which will call the method.
object
Forbidden for static methods, required for other methods.
Returns the newly created Closure .
Throws a ValueError if object
is null
but the method is non-static.
Throws a ReflectionException if object
is not an instance of the class this method was declared in.
Version | Description |
---|---|
8.0.0 |
object is now nullable.
|
You can call private methods with getClosure():
<?php
function call_private_method($object, $method, $args = array()) {
$reflection = new ReflectionClass(get_class($object));
$closure = $reflection->getMethod($method)->getClosure($object);
return call_user_func_array($closure, $args);
}
class Example {
private $x = 1, $y = 10;
private function sum() {
print $this->x + $this->y;
}
}
call_private_method(new Example(), 'sum');
?>
Output is 11.
Use method from another class context.
<?php
class A {
private $var = 'class A';
public function getVar() {
return $this->var;
}
public function getCl() {
return function () {
$this->getVar();
};
}
}
class B {
private $var = 'class B';
}
$a = new A();
$b = new B();
print $a->getVar() . PHP_EOL;
$reflection = new ReflectionClass(get_class($a));
$closure = $reflection->getMethod('getVar')->getClosure($a);
$get_var_b = $closure->bindTo($b, $b);
print $get_var_b() . PHP_EOL;
// Output:
// class A
// class B