深入理解PHP中的Closure::bind()和Closure::bindTo()

深入理解PHP中的Closure::bind()和Closure::bindTo()

方法理解

Closure::bind()是 Closure::bindTo() 的静态版本。

这里就拿Closure::bind()来讲吧。

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

不知道是不是因为翻译的问题,感觉“绑定指定的$this对象和类作用域。”不是很好理解

我是这么理解的:

绑定指定的$this对象:其实就是Closure::bind()方法的 第二个参数,请记住这个参数其实就是一个实例化后的对象,稍后会有例子讲解
绑定类作用域:其实就是Closure::bind()方法的第三个参数,请记住,这个参数通俗理解就是类名

这里按照不同参数来做个代码示例

1、只绑定实例化后的对象(官方:指定的$this对象)

<?php
/**
 * Created by PhpStorm.
 * User: Actor
 * Date: 2019-11-14
 * Time: 14:32
 */

$closure = function ($name, $age) {
    $this->name = $name;
    $this->age = $age;
};

class Person {
    public $name;
    public $age;

    public function say() {
        echo "My name is {$this->name}, I'm {$this->age} years old.\n";
    }
}

$person = new Person();

//把$closure中的$this绑定为$person
//这样在$bound_closure中设置name和age的时候实际上是设置$person的name和age
//也就是绑定了指定的$this对象($person)
$bound_closure = Closure::bind($closure, $person);

$bound_closure('xiaoming', 9);

$person->say();

运行后输出:

My name is xiaoming, I'm 9 years old.

2、只绑定类名(官方:类作用域)

<?php
/**
 * Created by PhpStorm.
 * User: Actor
 * Date: 2019-11-14
 * Time: 14:22
 */

$closure = function ($name, $age) {
    static::$name =  $name;
    static::$age = $age;

};

class Person {
    public static $name;
    public static $age;


    public static function say()
    {
        echo "My name is " . static::$name . ", I'm " . static::$age. " years old.\n";
    }
}

//把$closure中的static绑定为Person类
//这样在$bound_closure中设置name和age的时候实际上是设置Person的name和age
//也就是绑定了指定的static(Person)
$bound_closure = Closure::bind($closure, null, 'Person');

$bound_closure('xiaoming', 10);

Person::say();

运行后输出:

My name is xiaoming, I'm 10 years old.

3、同时绑定实例化后的对象和类名

<?php
/**
 * Created by PhpStorm.
 * User: Actor
 * Date: 2019-11-14
 * Time: 14:38
 */

$closure = function ($name, $age, $sex) {
    $this->name = $name;
    $this->age = $age;
    static::$sex = $sex;
};

class Person {
    public $name;
    public $age;

    static $sex;

    public function say()
    {
        echo "My name is {$this->name}, I'm {$this->age} years old.\n";
        echo "Sex: " . static::$sex . ".\n";
    }
}

$person = new Person();

//把$closure中的static绑定为Person类, $this绑定为$person对象
$bound_closure = Closure::bind($closure, $person, 'Person');
$bound_closure('xiaoming', 11, 'male');

$person->say();

运行后输出

My name is xiaoming, I'm 11 years old.
Sex: male.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值