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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-18
  • 2021-12-02
猜你喜欢
  • 2021-10-12
  • 2022-01-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-04
  • 2022-12-23
相关资源
相似解决方案