php匿名函数类(Closure)

2021-10-16
  1. 代表匿名函数的类
  2. 这个类带有一些方法允许在匿名函数创建后对其进行更多的控制

将匿名函数绑定到指定类上

  1. 复制当前闭包对象,绑定到指定的$this对象和类作用域。
  2. 绑定后可以使用指定类的方法和属性
class A {
    function __construct($val) {
        $this->val = $val;
    }
}

$c1 = function() { return $this->val; };

$ob1 = new A(1);

// 将匿名函数绑定在对象A的实例上
$c1 = $c1->bindTo($ob1,'A');
echo $c1(), "\n"; // 2

// 解除绑定
$c1 = $c1->bindTo(null);

将匿名函数绑定到指定类上--静态调用

class A {
    private static $sfoo = 1;
    private $ifoo = 2;
}
$cl1 = static function() {
    return A::$sfoo;
};
$cl2 = function() {
    return $this->ifoo;
};

// 将$cl1绑定在类A上
$bcl1 = Closure::bind($cl1, null, 'A');
// 将$cl2绑定在类A上
$bcl2 = Closure::bind($cl2, new A(), 'A');
echo $bcl1(), "\n"; // 1
echo $bcl2(), "\n"; // 2

// 解除绑定
$bcl1 = Closure::bind($bcl1, null);

将匿名函数绑定到指定类并直接调用

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

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

$closure = function ($delta) { var_dump($this->value + $delta); };

// 将$closure绑定到实例并直接执行$closure
$closure->call($three, 4); // 7
$closure->call($four, 4);  // 8

 

{/if}