fengzmh

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

分类:

技术点:

相关文章:

  • 2021-08-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-04-07
  • 2022-12-23
  • 2021-07-14
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-10
  • 2021-11-21
  • 2021-09-26
  • 2021-12-14
相关资源
相似解决方案