什么是闭包?
闭包和匿名函数其实不同的。匿名函数只是没有名字的函数,可能场景是用于便于调用。而闭包函数是引用外部的变量,导致延长了外部变量的生命周期的一个匿名函数。
PHP中的闭包函数
主要通过bind和bindTo函数
- PHP中闭包不支持构造函数
- bind(closure, [newthis], [newscope])
- closure_function::bindTo(newthis, [newscope])
函数解释
bind函数
-
- 第一个参数, 这个是闭包函数
-
- 第二个参数, 将这个闭包函数绑定到这个对象中。直白的讲就是如果闭包函数有 t h i s , 那 么 相 当 于 这 个 闭 包 函 数 就 是 这 个 对 象 的 方 法 ( 如 果 闭 包 函 数 没 有 this, 那么相当于这个闭包函数就是这个对象的方法(如果闭包函数没有 this,那么相当于这个闭包函数就是这个对象的方法(如果闭包函数没有this, 那么可以不绑定,直接写null)
-
- 相当于控制$this的权限,如果static(默认), 则无法访问类中私有属性和保护属性
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";
result:
1
2
bindTo函数
作用和bind类似, 复制当前闭包对象,绑定指定的$this对象和类作用域。但是其场景是将闭包函数当作Closure类的实例进行调用
- (必填)将这个闭包函数绑定到这个对象中。直白的讲就是如果闭包函数有 t h i s , 那 么 相 当 于 这 个 闭 包 函 数 就 是 这 个 对 象 的 方 法 ( 如 果 闭 包 函 数 没 有 this, 那么相当于这个闭包函数就是这个对象的方法(如果闭包函数没有 this,那么相当于这个闭包函数就是这个对象的方法(如果闭包函数没有this, 那么可以不绑定,直接写null)
- 相当于控制$this的权限,如果static(默认), 则无法访问类中私有属性和保护属性
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";
$cl = $cl->bindTo($ob2);
echo $cl(), "\n";