ReflectionMethod::getClosure

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

ReflectionMethod::getClosureこのメソッドに動的に作成されたクロージャを返す

説明

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

メソッドをコールするクロージャを作成します。

パラメータ

object

staticメソッドの場合は不要、その他のメソッドの場合は必須となります。

戻り値

新しく作成した Closure を返します。

エラー / 例外

objectnull なのに、 メソッドが static ではない場合、 ValueError がスローされます。

object が、 このメソッドが宣言されたクラスのインスタンスでない場合、 ReflectionException がスローされます。

変更履歴

バージョン 説明
8.0.0 object は、nullable になりました。
add a note

User Contributed Notes 2 notes

up
18
Denis Doronin
11 years ago
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.
up
-1
okto
7 years ago
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
To Top