PHP 闭包(Closure)【转载】

大佬地址:https://blog.csdn.net/wuxing26jiayou/article/details/51067190

例1:
介绍Closure::bind和Closure::bindTo。
Closure::bind是Closure::bindTo的静态版本,其说明如下:
public static Closure bind (Closure $closure , object $newthis [, mixed $newscope = ‘static’ ])
closure表示需要绑定的闭包对象。
newthis表示需要绑定到闭包对象的对象,或者NULL创建未绑定的闭包。
newscope表示想要绑定给闭包的类作用域,可以传入类名或类的示例,默认值是 ‘static’, 表示不改变。

该方法成功时返回一个新的 Closure 对象,失败时返回FALSE。

<?php 
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() {  

	#下面调用会报错Cannot access private property Animal::$dog ,此时是闭包原有作用域
    //return $this->dog; 
    
    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>';// cat|根据绑定规则,允许闭包通过作用域限定操作符获取Animal类静态私有成员属性  
echo $bindDog(),'<br>';// dog|根据绑定规则,允许闭包通过绑定的$this对象(Animal实例对象)获取Animal实例私有成员属性  
echo $bindPig(),'<br>';// pig|根据绑定规则,允许闭包通过绑定的$this对象获取Animal实例公有成员属性

// bindTo与bind类似,是面向对象的调用方式,这里只举一个,其他类比就可以
$bindCat = $cat->bindTo(null, 'Animal');

例2:

/** 
 * 给类动态添加新方法
 * 
 * @author 疯狂老司机(不是转载文章的我,哥们名字够刺激)
 */
trait DynamicTrait {
 
    /**
     * 自动调用类中存在的方法
     */
    public function __call($name, $args) {
        if(is_callable($this->$name)){
            return call_user_func($this->$name, $args);
        }else{
            echo "Method {$name} does not exist";
        }
    }
    /**
     * 添加方法
     */
    public function __set($name, $value) {
        $this->$name = is_callable($value)? 
            $value->bindTo($this, $this): 
            $value;
    }
}
 
/** 
 * 只带属性不带方法动物类
 * 
 * @author 疯狂老司机
 */
class Animal {
    use DynamicTrait;
    private $dog = 'dog';
}
 
$animal = new Animal;
 
// 往动物类实例中添加一个方法获取实例的私有属性$dog
$animal->getdog = function() { # 此时调用DynamicTrait 类下__set函数动态添加function
    return $this->dog;
};
 
echo $animal->getdog(); # 此时调用DynamicTrait 类下__call函数

总结:合理使用闭包能使代码更加简洁和精炼。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值