laravel學習筆記(七)singleton和bind方法的區別


singleton和bind都是返回一個類的實例,不同的是singleton是單例模式,而bind是每次返回一個新的實例。

1、singleton

class fun {
    public $strKey;
}

app()->singleton('fun', fun::class);
$fun1 = app()->make('fun');
$fun2 = app()->make('fun');
$fun1->strKey = "fun1";
$fun2->strKey = "fun2";
echo $fun1->strKey . '  ' . $fun2->strKey;

  最后獲取到的結果是fun2 fun2

2、bind

class fun {
    public $strKey;
}

app()->bind('fun', fun::class);
$fun1 = app()->make('fun');
$fun2 = app()->make('fun');
$fun1->strKey = "fun1";
$fun2->strKey = "fun2";
echo $fun1->strKey . '  ' . $fun2->strKey;

  最后獲取到的結果是fun1 fun2

再看框架底層代碼:

public function singleton($abstract, $concrete = null)
{
    $this->bind($abstract, $concrete, true);
}

發現singleton方法其實也是調用bind方法,只是最后一個參數是true,表示單例模式。框架源代碼:Illuminate/Container/Container.php


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM