1

此函数将确保对于非静态闭包,具有绑定实例将意味着作用域,反之亦然

什么?我读了 100 遍,我还是不明白。

4

2 回答 2

0

简而言之,它只是意味着您可以在闭包中使用 $this ,它将引用实例(如果有的话),而不必将 $this 重新分配给 $me 并通过 use () ...

(来自文档)

<?php

class A {
    function __construct($val) {
        $this->val = $val;
    }
    function getClosure() {
        //returns closure bound to this object and scope
        return function() { return $this->val; };
    }
}

$ob1 = new A(1);
$ob2 = new A(2);

$cl = $ob1->getClosure(); // $this in the closure will be $ob1
echo $cl(), "\n"; // thus printing 1
$cl = $cl->bindTo($ob2);  // $this in the closure will be changed (re-binded) to $ob2
echo $cl(), "\n"; // thus printing 2
?>
于 2013-11-12T10:55:55.547 回答
0

bindToset 是$this变量,它允许您将闭包重新绑定到不同的实例。例子:

<?php

// by default, in global scope $this is null
$cl = function() {
    return isset($this) && $this instanceof \DateTime ? $this->format(\DateTime::ISO8601) : 'null';
};

printf("%s\n", $cl()); // prints 'null'

// bind a new instance of this \Closure to an instance of \DateTime
$b = new \DateTime();
$cl = $cl->bindTo($b);

printf('%s\n', $cl()); // prints current date
于 2013-11-12T04:53:52.957 回答