search

Home  >  Q&A  >  body text

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

巴扎黑巴扎黑3022 days ago938

reply all(1)I'll reply

  • 面对疾风吧

    面对疾风吧2016-11-10 17:23:22

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

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

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

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


    reply
    0
  • Cancelreply