PHP Closure 类的bind简介和使用

1、Closure 类 的作用

面向对象变成语言代码的复用主要采用继承来实现,而函数的复用,就是通过闭包来实现。这就是闭包的设计初衷。

注:PHP里面闭包函数是为了复用函数而设计的语言特性,如果在闭包函数里面访问指定域的变量,使用use关键字来实现。

2、核心方法 bind  扩展一个类的功能,并能在外边可以使用类内部的私有属性(protected和provide )。看demo

class Student {
    private $name = "jim";
    protected $age = 38;

    public function say() {

    }
}
class Teacher {
    public $name = "Lucas";
    public $age = 4;

    public function say() {

    }
}


//创建需要共用的匿名函数
$closureFunc = function ($name,$age) {
    $this->name = $name;
    $this->age = $age;
    echo get_class($this).":My name is {$this->name}, I'm {$this->age} years old.
";

};

$student = new Student();
$teacher = new Teacher();

//把$closure中的$this绑定为$person
//这样在$bound_closure中设置name和age的时候实际上是设置$person的name和age
//也就是绑定了指定的$this对象($person)
$bound_teacher = Closure::bind($closureFunc, $teacher);//把对象$bound_teacher 指针绑定给匿名函数 $closureFunc ,让$closureFunc有访问对象属性的能力
$bound_student = Closure::bind($closureFunc, $student,"Student");//如果对象的属性是protected 或 private 还需要传第三参数:类名 “Student”


$bound_student('amy',37);//输出 Student:My name is amy, I'm 37 years old.
$bound_teacher('liangshaoxi',74);//输出 Teacher:My name is liangshaoxi, I'm 74 years old.
echo '$teacher->name:'.$teacher->name.PHP_EOL;//输出 $teacher->name:liangshaoxi   ,已经把对象$student 的私有属性name改为liangshaoxi

  

原文地址:https://www.cnblogs.com/jinshao/p/14880108.html