PHP 5.3+ 所有匿名函數自動實例化為 Closure 類對象:
$func = function() { echo 'hello'; };
var_dump($func); // object(Closure)#1 (0) { }
$ref = new ReflectionClass('Closure');
var_dump($ref->isInterface()); // false
var_dump($ref->isFinal()); // true (不可繼承)
var_dump($ref->isInternal()); // true (內部類)
複製閉包並綁定新 $this 與類作用域:
class Lang { private $name = 'PHP'; }
$closure = function() { return $this->name; };
$bound = Closure::bind($closure, new Lang(), 'Lang');
echo $bound(); // PHP
// 參數說明:
// $closure 原閉包
// $newThis 綁定的 $this 對象(null 為靜態閉包)
// $newScope 綁定的類作用域(可訪問 private/protected)
實例方法版本,鏈式調用友好:
$bound = $closure->bindTo(new Lang(), 'Lang');
echo $bound(); // PHP
new Closure(); // Fatal error: Cannot instantiate Closure
只能通過匿名函數語法或 bind/bindTo 創建。
class Invoker {
public function __invoke($x, $y) { return $x + $y; }
}
$obj = new Invoker;
echo $obj(3, 5); // 8
// 結合閉包:可調用對象統一介面
$callable = $obj;
$callable(10, 20); // 30
$container->set('db', function() {
return new PDO($dsn, $user, $pass);
});
// 獲取時才實例化
$db = $container->get('db');
$router->get('/user/{id}', function($id) {
return UserController::show($id);
})->bindTo(new UserController(), UserController::class);
$expensive = function() use ($heavyData) {
return compute($heavyData);
};
$cached = function() use ($expensive, &$cache) {
return $cache ?? ($cache = $expensive());
};
| 場景 | $this 可用性 | 訪問私有成員 |
|---|---|---|
| 類方法內定義 | 自動綁定當前 $this | 可訪問當前類 private |
| 靜態方法內定義 | 無 $this (靜態閉包) | 不可訪問實例成員 |
| bindTo($obj, 'Class') | 綁定指定 $obj | 可訪問 Class private |
| bindTo($obj, null) | 綁定指定 $obj | 僅 public |
| bindTo(null, 'Class') | 無 $this (靜態) | 可訪問 Class static private |
class A { private $val = 10; }
$cl = function($mul) { return $this->val * $mul; };
echo $cl->call(new A(), 5); // 50,臨時綁定調用,不產生新閉包對象
static 變數或類屬性替代bind/bindTo 創建新對象,避免循環中重複綁定Opis\Closure\SerializableClosure 庫支援