PHP 8.5.0 RC 2 available for testing

ReflectionMethod::getClosure

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

ReflectionMethod::getClosureDevuelve una función anónima creada dinámicamente para el método

Descripción

public ReflectionMethod::getClosure(?object $object = null): Closure

Crea una función anónima que llamará a este método.

Parámetros

object

Prohibido para los métodos estáticos, requerido para los demás métodos.

Valores devueltos

Devuelve un objeto Closure recién creado.

Errores/Excepciones

Genera una ValueError si object es null pero el método no es estático.

Genera una ReflectionException si object no es una instancia de la clase de la que este método fue declarado.

Historial de cambios

Versión Descripción
8.0.0 object ahora es nullable.
add a note

User Contributed Notes 2 notes

up
14
Denis Doronin
12 years ago
You can call private methods with getClosure():<?phpfunction 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.
up
-1
okto
9 years ago
Use method from another class context.<?phpclass 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
To Top