函式名:Closure::bind()
適用版本:5.4.0 及以上版本
用法:Closure::bind() 方法用於將閉包函式繫結到特定的物件上,從而改變閉包函式中 $this 變數的指向。
語法:
Closure::bind ( Closure $closure , object|null $newThis = null , mixed $newScope = "static" ) : Closure
引數:
$closure
:必需,要繫結的閉包函式。$newThis
:可選,要繫結到閉包函式中$this
的物件。若不指定,則$this
的指向不會改變。$newScope
:可選,要繫結到閉包函式中的靜態變數。預設情況下,將使用原始閉包函式的靜態變數。
返回值:返回一個新的繫結了物件和靜態變數的閉包函式。
示例:
class MyClass {
private $x = 1;
}
$getX = function() {
return $this->x;
};
$obj = new MyClass();
$boundGetX = Closure::bind($getX, $obj, 'MyClass');
echo $boundGetX(); // 輸出:1
在上面的示例中,我們定義了一個閉包函式 $getX
,它返回一個物件的私有變數 $x
的值。然後,我們建立了一個 MyClass
的例項 $obj
。透過使用 Closure::bind()
將閉包函式繫結到 $obj
物件上,並指定繫結的類為 MyClass
,使閉包中的 $this
指向了 $obj
。最後,透過呼叫繫結後的閉包函式 $boundGetX
,我們成功獲取了 $obj
物件的私有變數 $x
的值。