php 闭包的作用

WBOY
发布: 2023-03-02 09:30:01
原创
994 人浏览过

<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这个类;

这样写的好处的是,当$this['config']不被真正使用时,减少了额外实例化的过程和内存的消耗

closure会在真正调用的时候才new一个Config, 这样就可以实现了lazy load.

除了上面的懒加载, 还有一个好处是实现了一个工厂模式 -- 每次拿config都是新new出来的

1、懒加载大家都说到了

2、其实匿名函数很大程度上函数式编程的一个体现

相关标签:
php
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!