Closure::bind 复制一个闭包,绑定指定的$this对象和类作用域。

public static Closure Closure::bind ( Closure $closure , object $newthis [, mixed $newscope = 'static' ] )

参数说明:分别是函数-对象-范围

  $closure 需要绑定的匿名函数

 $newthis 需要绑定到匿名函数的对象,或者 NULL 创建未绑定的闭包。(个人理解:如果要用闭包中的$this,这个对象就表示$this)

 $newscope 想要绑定给闭包的类作用域,或者 'static' 表示不改变。如果传入一个对象,则使用这个对象的类型名。 类作用域用来决定在闭包中 $this 对象的 私有、保护方法 的可见性。(个人理解:如果没有传入对象,则匿名函数只能访问$newthis中的public方法,如果传入对象,则匿名函数可以访问$newthis对象中的public,protected,private方法)

下面例子只绑定对象:

$closure = function ($name,$age){
    $this->name = $name;
    $this->age = $age;
};
class Person{
    public $name;
    public $age;
    public function getInfo(){
        echo "姓名:{$this->name},年龄:{$this->age}";
    }
}
$person = new Person();
$closure_bind = Closure::bind($closure,$person);
$closure_bind("老王",50);
$person->getInfo();
//结果:姓名:老王,年龄:50
  下面例子只绑定作用域
$closure = function ($name,$age){
    static::$name = $name;
    static::$age = $age;
};
class Person{
    static $name;
    static $age;
    public function getInfo(){
        echo "姓名:".self::$name.",年龄:".self::$age."<br />";

    }
}
$person = new Person();
$closure_bind = Closure::bind($closure,null,Person::class);
$closure_bind("老张","40");
$person->getInfo();
//结果:姓名:老张,年龄:40
同时绑定对象和作用域
$closure = function ($name,$age){
    $this->name = $name;
    static::$age = $age;
};
class Person{
    public $name;
    static $age;
    public function getInfo(){
        echo "姓名:".$this->name.",年龄:".self::$age;

    }
}
$person = new Person();
$closure_bind = Closure::bind($closure,$person,Person::class);
$closure_bind("小李","20");
$person->getInfo();
//结果:姓名:小李,年龄:20
既不绑定作用域也不绑定对象的,这里就不讨论了,意义不大.

下面例子,体现了第三个参数的个人理解

class Authority{
    private function private_method(){
        echo "private...<br/>";
    }
    protected function protected_method(){
        echo "protected...<br/>";
    }
    public function public_method(){
        echo "public...<br/>";
    }
}
$obj = new Authority();
//$bind = Closure::bind(function (){
//    $this->private_method();
//    $this->protected_method();
//    $this->public_method();
//},$obj);  //报错,没权限访问
$bind = Closure::bind(function (){
    $this->private_method();
    $this->protected_method();
    $this->public_method();
},$obj,Authority::class); //Authority::class可以用new Authority()
$bind();
//结果如下
private...
protected...
public...


   




猜你喜欢

转载自blog.csdn.net/weixin_37909391/article/details/79746027