美文网首页
闭包 | 匿名函数

闭包 | 匿名函数

作者: 我Bug写的太好了 | 来源:发表于2019-04-24 11:33 被阅读0次

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

 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实例公有成员属性

延迟加载

    class Log
    {
        public function write()
        {
            echo '写入日志';
        }
    }

    class Test
    {
        // 通过构造函数传参创建闭包, `new Log` 不会马上执行 
        public function __construct($name)
        {
            $this->bind['log'] = function () use ($name) {

                return new $name();
            };
        }

        // 调用闭包, 通过 $this当前对象 返回 Log 实例化  
        public function execute()
        {
            return $this->bind['log']($this);
        }
    }

    $test = new Test('Log');
    $log  = $test->execute();
    $log->write();

相关文章

网友评论

      本文标题:闭包 | 匿名函数

      本文链接:https://www.haomeiwen.com/subject/ylbwgqtx.html