php闭包类外操作私有属性

闭包类外操作类的属性

Closure::bind()

Closure::bindTo();

class person{    private $age;    private $sex;    public function __construct($age,$sex){        $this->age=$age;        $this->sex=$sex;
    }    public function getage(){        return $this->age;
    }    public function getclosure(){        return function() {                return $this->age . "-->" . $this->sex;
            };

    }

}$tom=new person(18,1);$lucy=new person(16,2);$set=Closure::bind(function($obj,$k,$v){    $obj->$k=$v;
},null,person::class);$get=Closure::bind(function($obj,$k){    return $obj->$k;
},null,person::class);$get_tom_age=Closure::bind(function() use($tom){    return $tom->age;
},null,person::class);echo $get_tom_age();//18echo $get($tom,'age');//18$set($tom,'age',20);echo $get($tom,'age');//20$c1=$tom->getclosure();echo $c1();//20-->1$c1=$c1->bindTo($lucy);echo $c1();//16-->2

 

上一篇:google closure libary 三剑客


下一篇:SwiftUI 内功教程之Closures 07 Trailing Closures尾随闭包及经典用法