<code> 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);
有什么优势?</code><code> 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);
有什么优势?</code>
惰加载。这两种写法都可以,但是。$this['config'] = new config($config);
这种方式,当你给$this->['config']赋值的时候,即进行了new config($config)操作。
<code class="php">$this['config'] = function () use ($config) {
return new Config($config);
}</code>这种方式,你只是给$this->['config']一个匿名函数,当你要用到的时候,才会进行new Config($config)的操作。
不知道我这种解释对不对= =比较不善表达= =
<code>能不能直接写成这样: $this['config'] = new Config($config); 有什么优势?</code>
完全可以写成这样,只不过每次在实例化的时候都会去new Config这个类,并不管用不用的到;
<code>$this['config'] = function () use ($config) {
return new Config($config);
}</code>这种写法呢,是给$this['config']声明了一个匿名函数,当$this['config']被真正调用的时候才会去new Config这个类;
立即学习“PHP免费学习笔记(深入)”;
这样写的好处的是,当$this['config']不被真正使用时,减少了额外实例化的过程和内存的消耗
closure会在真正调用的时候才new一个Config, 这样就可以实现了lazy load.
除了上面的懒加载, 还有一个好处是实现了一个工厂模式 -- 每次拿config都是新new出来的
1、懒加载大家都说到了
2、其实匿名函数很大程度上函数式编程的一个体现
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号