登陆

php 闭包的作用

 public function __construct($config)
    {    parent::__construct();    $this['config'] = function () use ($config) {        return new Config($config);
    };
    ...
    其中    $this['config'] = function () use ($config) {        return new Config($config);
    能不能直接写成这样:    $this['config'] = new Config($config);
    有什么优势?


# PHP
高洛峰高洛峰1833 天前423 次浏览

全部回复(1)我要回复

  • 三叔

    三叔2016-11-07 14:02:05

    惰加载。这两种写法都可以,但是。
    $this['config'] = new Config($config);
    这种方式,当你给$this->['config']赋值的时候,即进行了new Config($config)操作。

    $this['config'] = function () use ($config) { 
          return new Config($config);
    }

    这种方式,你只是给$this->['config']一个匿名函数,当你要用到的时候,才会进行new Config($config)的操作。

    不知道我这种解释对不对= =比较不善表达= =


    回复
    0
  • 取消回复发送