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學習者快速成長!