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
标签:function,Closure,私有,age,sex,person,tom,php,闭包类 来源: https://blog.51cto.com/u_10182395/2756456