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); 有什么优势?
回复内容: 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); 有什么优势?
惰加载。这两种写法都可以,但是。
$this['config'] = new config($config);
这种方式,当你给$this->['config']赋值的时候,即进行了new config($config)操作。
$this['config'] = function () use ($config) { return new config($config);}
这种方式,你只是给$this->['config']一个匿名函数,当你要用到的时候,才会进行new config($config)的操作。
不知道我这种解释对不对= =比较不善表达= =
能不能直接写成这样:$this['config'] = new config($config);有什么优势?
完全可以写成这样,只不过每次在实例化的时候都会去new config这个类,并不管用不用的到;
$this['config'] = function () use ($config) { return new config($config);}
这种写法呢,是给$this['config']声明了一个匿名函数,当$this['config']被真正调用的时候才会去new config这个类;
这样写的好处的是,当$this['config']不被真正使用时,减少了额外实例化的过程和内存的消耗
closure会在真正调用的时候才new一个config, 这样就可以实现了lazy load.
除了上面的懒加载, 还有一个好处是实现了一个工厂模式 -- 每次拿config都是新new出来的
1、懒加载大家都说到了
2、其实匿名函数很大程度上函数式编程的一个体现