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


  • 2021-01-16 09:45:19

    tabbar的titlePositionAdjustment设置文字距离

    指定相应的数据去偏移一个位置,向右或者向下为正值,向左或者向上为负值,不过首先你得有一个相对位置的坐标。而tabbarItem文字的坐标是底部为x轴,y轴则是tabbarItem的centerX;

  • 2021-01-16 09:49:13

    Cocoapods如何查看项目中引入库的版本号

    项目中已经安装过Cocoapods,并生成了Podfile.lock文件。 打开终端,cd命令切换到项目中的Podfile.lock文件目录下,执行命令:cat Podfile.lock 即可。也可以用文本方式打开 Podfile.lock 文件。示例如下:

  • 2021-01-18 13:50:21

    vue实现粘贴功能

    paste事件就是粘贴事件 需要通过clipboardData获得粘贴的内容

  • 2021-01-18 15:12:57

    flex和inline-flex区别

    flex: 将对象作为弹性伸缩盒显示 inline-flex:将对象作为内联块级弹性伸缩盒显示