Advantages: reduce the relationship between classes and classes
Container:
1. Reduce the coupling between classes
2. Realize lazy loading (which class needs to be created again which class)
3. Easy to manage
<?php
//轮胎类=》汽车类
class LunTai
{
function roll()
{
echo "轮胎在转动\n";
}
}
//class BMW
//{
// public function run()
// {
// $luntai = new LunTai();
// $luntai->roll();
// echo "开着宝马玩\n";
// }
//}
//普通方式
//$bmw = new BMW();
//$bmw->run();
//依赖注入
class BMW
{
protected $luntai;
function __construct($luntai)
{
$this->luntai = $luntai;
}
function run()
{
$this->luntai->roll();
echo "开着宝马玩\n";
}
}
//
//$luntai = new LunTai();
//$bmw = new BMW($luntai);
//$bmw->run();
//容器
class Container
{
//存放所绑定的类
static $register = [];
//绑定函数
static function bind($className,Closure $closure)
{
self::$register[$className] = $closure;
}
//创建对象函数
static function make($name)
{
$closure = self::$register[$name];
return $closure();
}
}
Container::bind('LunTai',function (){
return new LunTai();
});
Container::bind('BMW',function (){
return new BMW(Container::make('LunTai'));
});
$bmw = Container::make('BMW');
$bmw->run();