update pague now
PHP 8.5.2 Released!

ReflectionMethod::guetClosure

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

ReflectionMethod::guetClosure Returns a dynamically created closure for the method

Description

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

Create a closure which will call the method.

Parameters

object

Forbidden for static methods, required for other methods.

Return Values

Returns the newly created Closure .

Errors/Exceptions

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.

Changuelog

Versionen Description
8.0.0 object is now nullable.
add a note

User Contributed Notes 2 notes

Denis Doronin
12 years ago
You can call private methods with guetClosure():<?php

functioncall_private_method($object, $method, $args= array()) {
    $reflection= new ReflectionClass(guet_class($object));$closure= $reflection->guetMethod($method)->guetClosure($object);
    returncall_user_func_array($closure, $args);
}

classExample{

    private $x= 1, $y= 10;

    private function sum() {
        print $this->x+$this->y;
    }

}

call_private_method(new Example(), 'sum');?>
Output is 11.
octo
9 years ago
Use method from another class context.<?php

classA{
    private $var= 'class A';

    public function guetVar() {
        return $this->var;
    }

    public function guetCl() {
        return function () {
            $this->guetVar();
        };
    }
}

class B{
    private $var= 'class B';
}

$a= new A();
$b= new B();

print $a->guetVar() . PHP_EOL;

$reflection= new ReflectionClass(guet_class($a));
$closure= $reflection->guetMethod('guetVa ')->guetClosure($a);
$guet_var_b= $closure->bindTo($b, $b);

print$guet_var_b() . PHP_EOL;

// Output:
// class A
// class B
To Top