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();//18



echo $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

 

posted @ 2018-03-28 23:14  H&K  阅读(682)  评论(0编辑  收藏  举报