php中Closure的bind和bindTo

bind是bindTo的静态版本,因此只说bind吧。(不是太了解为什么要弄出两个版本)

官方文档: 复制一个闭包,绑定指定的$this对象和类作用域。

其实后半句表述很不清楚。 我的理解: 把一个闭包转换为某个类的方法(只是这个方法不需要通过对象调用), 这样闭包中的$this、static、self就转换成了对应的对象或类。

 

因为有几种情况:

1、只绑定$this对象.
2、只绑定类作用域.
3、同时绑定$this对象和类作用域.(文档的说法)
4、都不绑定.(这样一来只是纯粹的复制, 文档说法是使用cloning代替bind或bindTo)

下面详细讲解这几种情况:

1、只绑定$this对象

 1 $closure = function ($name, $age) {
 2     $this->name = $name;
 3     $this->age = $age;
 4 };
 5  
 6 class Person {
 7     public $name;
 8     public $age;
 9  
10     public function say() {
11         echo "My name is {$this->name}, I'm {$this->age} years old.\n";
12     }
13 }
14  
15 $person = new Person();
16  
17 //把$closure中的$this绑定为$person
18 //这样在$bound_closure中设置name和age的时候实际上是设置$person的name和age
19 //也就是绑定了指定的$this对象($person)
20 $bound_closure = Closure::bind($closure, $person);
21  
22 $bound_closure('php', 100);
23 $person->say();

注意: 在上面的这个例子中,是不可以在$closure中使用static的,如果需要使用static,通过第三个参数传入带命名空间的类名。

2、只绑定类作用域.

 1 $closure = function ($name, $age) {
 2   static::$name =  $name;
 3   static::$age = $age;
 4 };
 5  
 6 class Person {
 7     static $name;
 8     static $age;
 9  
10     public static function say()
11     {
12         echo "My name is " . static::$name . ", I'm " . static::$age. " years old.\n";
13     }
14 }
15  
16 //把$closure中的static绑定为Person类
17 //这样在$bound_closure中设置name和age的时候实际上是设置Person的name和age
18 //也就是绑定了指定的static(Person)
19 $bound_closure = Closure::bind($closure, null, Person::class);
20  
21 $bound_closure('php', 100);
22  
23 Person::say(); 

注意: 在上面的例子中,是不可以在$closure中使用$this的,因为我们的bind只绑定了类名,也就是static,如果需要使用$this,新建一个对象作为bind的第二个参数传入。

3、同时绑定$this对象和类作用域.(文档的说法)

 1 $closure = function ($name, $age, $sex) {
 2     $this->name = $name;
 3     $this->age = $age;
 4     static::$sex = $sex;
 5 };
 6  
 7 class Person {
 8     public $name;
 9     public $age;
10  
11     static $sex;
12  
13     public function say()
14     {
15         echo "My name is {$this->name}, I'm {$this->age} years old.\n";
16         echo "Sex: " . static::$sex . ".\n";
17     }
18 }
19  
20 $person = new Person();
21  
22 //把$closure中的static绑定为Person类, $this绑定为$person对象
23 $bound_closure = Closure::bind($closure, $person, Person::class);
24 $bound_closure('php', 100, 'female');
25  
26 $person->say();

在这个例子中可以在$closure中同时使用$this和static

4、都不绑定.(这样一来只是纯粹的复制, 文档说法是使用cloning代替bind或bindTo)

1 $closure = function () {
2     echo "bind nothing.\n";
3 };
4  
5 //与$bound_closure = clone $closure;的效果一样
6 $bound_closure = Closure::bind($closure, null);
7  
8 $bound_closure();

这个就用clone好了吧…

内容转载自: https://www.cnblogs.com/eleven24/p/7487923.html

 

posted @ 2018-04-18 16:58  初心未泯  阅读(135)  评论(0编辑  收藏  举报