zoukankan      html  css  js  c++  java
  • 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): 相当于类和实例调用的区别,函数的作用域, 传类表示静态调用方式,内部可以“类名::属性”的方式使用;实例表示实例调用方式,内部可以“->”
  • 相关阅读:
    SVN: repository browser 库浏览器
    创业泡沫真他妈的大出血来了 --个人需要创业以谋生,行业需要创业以求变,国家需要创业以维稳
    判断输入的是否是大于0的正整数
    linux开放或限制端口和ip访问
    linux模糊删除es索引脚本
    ssh免密登录
    DES加密解密
    SpringBoot 单元测试
    SpringContextHolder 工具类
    fiddler抓包 443 请求不到数据
  • 原文地址:https://www.cnblogs.com/one-villager/p/8423097.html
Copyright © 2011-2022 走看看