簡體   English   中英

什么是PHP中的Closure :: bind()

[英]What is Closure::bind() in PHP

PHP手冊沒有提供關於Closure :: bind()的解釋,這個例子也令人困惑。

這是網站上的代碼示例:

class A {
private static $sfoo = 1;
private $ifoo = 2;
}
$cl1 = static function() {
return A::$sfoo;
};
$cl2 = function() {
return $this->ifoo;
};

$bcl1 = Closure::bind($cl1, null, 'A');
$bcl2 = Closure::bind($cl2, new A(), 'A');
echo $bcl1(), "\n";
echo $bcl2(), "\n";

Closure :: bind()的參數是什么?

上面使用了Null,甚至使用了“new”關鍵字,這讓我更加困惑。

如果將$cl2的值作為類A的方法,則該類如下所示:

class A {
    public $ifoo = 2;

    function cl2()
    {
        return $this->ifoo;
    }
}

你可以像這樣使用它:

$x = new A();
$x->cl2();
# it prints
2

但是,因為$cl2是一個閉包而不是A類的成員,所以上面的用法代碼不起作用。

Closure::bindTo()允許使用閉包,因為它是A類的方法:

$cl2 = function() {
    return $this->ifoo;
};

$x = new A();
$cl3 = $cl2->bindTo($x);
echo $cl3();
# it prints 2

$x->ifoo = 4;
echo $cl3();
# it prints 4 now

閉包使用$this的值但$this未在$cl2定義。 $cl2()運行時, $thisNULL並且它會觸發錯誤( “PHP致命錯誤:在不在對象上下文中時使用$this )。

Closure::bindTo()創建一個新的閉包,但它將這個新閉包內的$this的值“綁定”到它接收的對象作為其第一個參數。

$cl3存儲的代碼中, $this與全局變量$x具有相同的值。 $cl3()運行時, $this->ifoo是對象$xifoo的值。

Closure::bind()Closure::bindTo()的靜態版本。 它與Closure::bindTo()具有相同的行為,但需要一個額外的參數:第一個參數必須是要綁定的閉包。

如果您更喜歡使用靜態版本,請嘗試

$cl4 = Closure::bind(function () { return $this->ifoo; }, new A(), 'A');
echo $cl4();
// it returns "2"

如果你想更新一個對象的屬性,它很酷,但是沒有'setter'屬性。 例如:

class Product {
  private $name;
  private $local;
  public function __construct(string $name) {
    $this->name = $name;
    $this->local = 'usa':
  }
}
$product1 = new Product('nice product');
echo $product1->local;
// it returns 'usa'

$product2 = \Closure::bind(function () {
  $this->local = 'germany';
  return $this;
}, new Product('nice product'), 'Product');
echo $product2->local;
// it returns 'germany'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM