PHP7之Closure::call()

Closure 类:匿名函数(在 PHP 5.3 中被引入)会产生这个类型的对象。
可将该类绑定到类或者对象上,即将自定义的方法动态添加到类或者对象上

php7之前使用的方法

  • Closure::bind :复制一个闭包,绑定指定的$this对象和类作用域。这个方法是 Closure::bindTo() 的静态版本

  • Closure::bindTo :复制当前闭包对象,绑定指定的$this对象和类作用域。创建并返回一个 匿名函数, 它与当前对象的函数体相同、绑定了同样变量,但可以绑定不同的对象,也可以绑定新的类作用域。

php7添加

  • Closure::call() : 方法被添加作为临时绑定的对象范围,以封闭并简便调用它的方法。它的性能相比PHP5.6 bindTo要快得多。
//bind.php
<?php
/** * Created by PhpStorm. * User: bee * Date: 2016/4/24 * Time: 22:35 */
class A {
    private static $sta = 1;
    private $com = 2;
}
$cl1 = static function() {
    return A::$sta;
};
$cl2 = function() {
    return $this->com;
};

$bcl1 = Closure::bind($cl1, null, 'A');
$bcl2 = Closure::bind($cl2, new A(), 'A');
echo $bcl1(), "\n";
echo $bcl2(), "\n";
<?php
//bindTo.php
/** * Created by PhpStorm. * User: bee * Date: 2016/4/24 * Time: 22:35 */
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();
echo $cl(), "\n";

$add = function(){
    return $this->val+1;
};
$cl = $add->bindTo($ob2);
//与call相比,需要增加()方可被调用
echo $cl(), "\n";
<?php
//call.php
/** * Created by PhpStorm. * User: bee * Date: 2016/4/24 * Time: 22:35 */
class Value {
    protected $value;

    public function __construct($value) {
        $this->value = $value;
    }

    public function getValue() {
        return $this->value;
    }
}

$three = new Value(3);
$four = new Value(4);

$closure = function ($delta) { return $this->getValue() + $delta; };
//可直接调用,不用在后面增加()
echo $closure->call($three, 3);
echo $closure->call($four, 4);

你可能感兴趣的:(PHP,闭包)