首页 >社区问答列表 >php 闭包的作用

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);
   有什么优势?

  • 面对疾风吧
  • 面对疾风吧    2016-11-10 17:23:221楼

    惰加载。这两种写法都可以,但是。
    $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添加回复

  • 回复