PHP Conference Japan 2024

ReflectionMethod::getClosure

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

ReflectionMethod::getClosure傳回方法的動態建立的閉包

說明

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

建立一個將呼叫該方法的閉包。

參數

object

靜態方法禁止使用,其他方法則必須使用。

傳回值

傳回新建立的 Closure

錯誤/例外

如果 objectnull 但方法不是靜態方法,則會拋出 ValueError 例外。

如果 object 不是宣告此方法的類別的實例,則會拋出 ReflectionException 例外。

更新日誌

版本 說明
8.0.0 object 現在可以為 null。

另請參閱

新增註釋

使用者貢獻的註釋 2 則註釋

Denis Doronin
11 年前
您可以使用 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');

?>

輸出為 11。
okto
8 年前
在另一個類別的上下文中使用這個方法。

<?php

類別 A {
私有
$var = 'class A';

公開 函數
getVar() {
返回
$this->var;
}

公開 函數
getCl() {
返回 function () {
$this->getVar();
};
}
}

類別
B {
私有
$var = 'class B';
}

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

印出
$a->getVar() . PHP_EOL;

$reflection = new ReflectionClass(get_class($a));
$closure = $reflection->getMethod('getVar')->getClosure($a);
$get_var_b = $closure->bindTo($b, $b);

印出
$get_var_b() . PHP_EOL;

// 輸出:
// class A
// class B
To Top