laravel singleton和bind方法的区别

2020-02-19 23:58:51

参考地址 laravel学习笔记(七)singleton和bind方法的区别

singleton和bind都是返回一个类的实例,不同的是singleton是单例模式,而bind是每次返回一个新的实例。

1、singleton

1
2
3
4
5
6
7
8
9
10
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

1
2
3
4
5
6
7
8
9
10
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

再看框架底层代码:

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

发现singleton方法其实也是调用bind方法,只是最后一个参数是true,表示单例模式。框架源代码:Illuminate/Container/Container.php


  • 2019-04-18 14:49:20

    Android图片加载框架最全解析,带你全面了解Glide 4的用法

    Glide的最新版本已经出到了4.4.0,可以说Glide 4已经是相当成熟和稳定了。而且也不断有朋友一直在留言,想让我讲一讲Glide 4的用法,因为Glide 4相对于Glide 3改动貌似还是挺大的,学完了Glide 3再去使用Glide 4,发现根本就无法使用。

  • 2019-04-23 13:57:37

    replace js 替换全部替换第一个

    RegExp("12333", "g"); 第一个参数是想要替换的内容 第二个参数“g”是匹配全部的意思,也可以换成"t",就是匹配第一个

  • 2019-04-25 15:40:16

    JS对象是否拥有某属性如何判断

    原型链上继承过来的属性无法通过hasOwnProperty检测到,返回false。 需注意的是,虽然in能检测到原型链的属性,但for in通常却不行。