PHP文档说明:Closure :: bindTo

时间:2013-11-12 04:11:45

标签: php closures

  

此函数将确保对于非静态闭包,具有   绑定实例意味着限制范围,反之亦然

什么?我读了100次,但我仍然不明白。

2 个答案:

答案 0 :(得分:0)

bindTo设置$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

答案 1 :(得分: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
?>