函式名稱:Closure::bindTo()
適用版本:PHP 5 >= 5.4.0, PHP 7
函式描述:該函式用於將閉包繫結到一個新的物件或類,並返回繫結後的閉包。
用法:
Closure::bindTo(callable $closure, object|null $newthis, object|string|null $newscope = null) : Closure
引數:
- $closure(必選):要繫結的閉包函式。
- $newthis(可選):要繫結的新物件或類的例項。
- $newscope(可選):要繫結到的新類物件或類名。
返回值:
該方法返回一個新的閉包。如果繫結失敗,則返回 false
。
示例:
class Foo {
private $name = 'John';
}
$name = 'Mary';
$anonymous = function() use ($name) {
echo $this->name . ' ' . $name;
};
$foo = new Foo();
$boundClosure = $anonymous->bindTo($foo, 'Foo');
$boundClosure(); // 輸出:John Mary
在上面的例子中,我們定義了一個匿名函式 $anonymous
,該函式使用了外部變數 $name
和 $this->name
。
然後,我們建立了一個 Foo
類的例項 $foo
。
使用 bindTo()
方法,將閉包函式 $anonymous
繫結到 $foo
物件,並指定繫結到 Foo
類的作用域。
最後,呼叫繫結後的閉包 $boundClosure
,會輸出 John Mary
。這是因為 $this->name
訪問了繫結後的物件 $foo
的私有屬性 name
,而 $name
訪問了 bindTo()
繫結前的外部變數。