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
