Closure::bind()

方法理解

官方解释:复制一个闭包,绑定指定的$this对象和类作用域。
我的理解:将闭包所需要的参数以$this对象或者的形式绑定进来。

这里按照不同参数来做个代码示例

第一种:只绑定实例化后的对象(官方:指定的$this对象)

<?php
$closure = function ($value){
    $this->value = $value;
};

class Test{
    public $value;
    function echoValue(){
        echo  $this->value;
    }
}

$test = new  Test();
$bound_closure = Closure::bind($closure,$test);
$bound_closure("ddd");
$test->echoValue();    

运行以上代码输出如下:

ddd

第二种:只绑定类名(官方:类作用域)

<?php
$closure = function ($value){
    static::$value = $value;
};

class Test{
    public static $value;
    public  static  function  echoValue(){
        echo  static::$value;
    }
}

$bound_closure = Closure::bind($closure,null,'Test');
$bound_closure("vvv");
Test::echoValue();

运行以上代码输出如下:

vvv

第三种:同时绑定

<?php
$closure = function ($value1,$value2){
    static::$value1 = $value1;
    $this->value2 = $value2;
};

class Test{
    public static $value1;
    public $value2;
    public function  echoValue(){
        echo  static::$value1."<br>";
        echo  $this->value2;
    }
}

$test = new Test();
$bound_closure = Closure::bind($closure,$test,'Test');
$bound_closure("ddd","vvv");
$test->echoValue();

运行以上代码输出如下:

ddd
vvv

推荐阅读更多精彩内容