php中 Closure::bind

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

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

参数

closure :需要绑定的匿名函数

newthis: 需要绑定到匿名函数的对象,或者null创建未绑定的闭包

newscope 想要绑定给闭包的类作用域,或者'static' 表示不改变。如果传入一个对象,则使用这个对象的类型名。类作用域用来决定在闭包中$this对象的私有,保护方法的可见性

返回值

返回一个新的Closure对象 或者在失败时返回false

<?php

class Person{

    public  $name = "张三";
    private $school = "北大";
    public  static  $age = "18cm";
    protected  $gf = "凤姐";
}
$name = function (){
    return $this->name;
};
$name1 = Closure::bind($name,new Person,null);
echo $name1();
echo "<hr>";
$school = function (){
    return $this->school;
};
$school1 = Closure::bind($school,new Person(),'Person');
echo $school1();
echo "<hr>";
$age  = static function (){
    return Person::$age;
};
$age1 = Closure::bind($age,  null,null);
echo $age1();
echo "<hr>";
$gf = function(){
    return $this->gf;
};
$gf1 = Closure::bind($gf,new Person(),'Person');
echo $gf1();

总结

 一般在匿名函数中有$this->name 类似这样用$this访问属性时,在使用bind绑定时候,第二个参数肯定要写,写出你绑定那个对象实例,第三个参数取决于你要访问的这个属性的可见性。如果是private,protected,则必须要写。如果本来就是公有的,则可以省略不写。

一般匿名函数中是 类目::静态属性,类似这样的访问方式,第二个参数可以写null,也可以写具体的对象实例,第三个参数和上面一样,如果这个静态属性的可见性是private或者protected,第三个参数必须要写,如果是public则可以省略不写。

 

 

 

参考链接

https://blog.csdn.net/qq_27718961/article/details/91043221

 

https://www.php.net/manual/zh/closure.bind.php

 

posted @ 2021-05-24 17:10  X__cicada  阅读(63)  评论(0编辑  收藏  举报