【问题标题】:What is Closure::bind() in PHP什么是 PHP 中的 Closure::bind()
【发布时间】:2018-02-24 18:46:51
【问题描述】:

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”关键字,这让我更加困惑。

【问题讨论】:

  • 检查bindTo()。这里还有一些解释。 bind() 只是静态版本

标签: php closures


【解决方案1】:

如果将$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 是对象ifoo$x 的值。

Closure::bind()Closure::bindTo() 的静态版本。它与Closure::bindTo() 具有相同的行为,但需要一个额外的参数:第一个参数必须是要绑定的闭包。

【讨论】:

    【解决方案2】:

    如果您喜欢使用静态版本,请尝试

    $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'
    

    【讨论】:

      猜你喜欢
      • 2021-09-06
      • 2014-03-23
      • 1970-01-01
      • 2013-08-10
      • 2013-02-04
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      相关资源
      最近更新 更多