PHP闭包之bind和bindTo

PHP闭包之bind和bindTo

Closure类摘要如下:

Closure {  
    __construct ( void )  
    public static Closure bind (Closure $closure , object $newthis [, mixed $newscope = 'static'] 
    public Closure bindTo (object $newthis [, mixed $newscope = 'static' ])
}

方法说明:

Closure::__construct — 用于禁止实例化的构造函数
Closure::bind — 复制一个闭包,绑定指定的$this对象和类作用域。
Closure::bindTo — 复制当前闭包对象,绑定指定的$this对象和类作用域。

闭包之bind方法

一个实例

<?php
/** 
 * 复制一个闭包,绑定指定的$this对象和类作用域。 
 * 
 * @author 疯狂老司机 
 */
class Animal {
    private static $cat = "cat";
    private $dog = "dog";
    public $pig = "pig";
}

/* 
 * 获取Animal类静态私有成员属性
 */
$cat = static function() {
    return Animal::$cat;
};

/* 
 * 获取Animal实例私有成员属性
 */
$dog = function() {
    return $this->dog;
};

/* 
 * 获取Animal实例公有成员属性
 */
$pig = function() {
    return $this->pig;
};

$bindCat = Closure::bind($cat, null, new Animal());// 给闭包绑定了Animal实例的作用域,但未给闭包绑定$this对象
$bindDog = Closure::bind($dog, new Animal(), 'Animal');// 给闭包绑定了Animal类的作用域,同时将Animal实例对象作为$this对象绑定给闭包
$bindPig = Closure::bind($pig, new Animal());// 将Animal实例对象作为$this对象绑定给闭包,保留闭包原有作用域
echo $bindCat(),'<br>';// 根据绑定规则,允许闭包通过作用域限定操作符获取Animal类静态私有成员属性
echo $bindDog(),'<br>';// 根据绑定规则,允许闭包通过绑定的$this对象(Animal实例对象)获取Animal实例私有成员属性
echo $bindPig(),'<br>';// 根据绑定规则,允许闭包通过绑定的$this对象获取Animal实例公有成员属性

总结:

  • bind函数:
    • 参数1($closure) : 表示闭包函数
    • 参数2($newthis): 相当于在函数内/外调用的区别,传类的实例表示在内部调用,NULL相当于在外部调用
    • 参数3($newscope): 相当于类和实例调用的区别,函数的作用域, 传类表示静态调用方式,内部可以“类名::属性”的方式使用;实例表示实例调用方式,内部可以“->”
posted @ 2018-02-06 16:53  oneVillager  阅读(4475)  评论(0编辑  收藏  举报
打赏

喜欢请打赏

扫描二维码打赏