class Luntai
{
public function roll()
{
echo '车轮在滚动<hr>';
}
}
class BMW
{
public function run()
{
$Luntai = new Luntai();
$Luntai->roll();
echo '开着宝马<hr>';
}
}
$BMW = new BMW();
$BMW->run();//"车轮在滚动<hr>" "开着宝马<hr>"
依赖注入(DI):不直接在类里new另外一个类,而是通过参数注入的方式。优点:减少类与类之间的联系
class Luntai
{
public function roll()
{
echo '车轮在滚动<hr>';
}
}
class BMW
{
protected $luntai;
public function __construct($luntai)
{
$this->luntai = $luntai;
}
public function run()
{
$this->luntai->roll();
echo '开着宝马<hr>';
}
}
$BMW = new BMW(new Luntai());
$BMW->run();//"车轮在滚动<hr>" "开着宝马<hr>"
容器:优点:降低耦合度;实现惰性加载;便于管理
class Luntai
{
public function roll()
{
echo '车轮在滚动<hr>';
}
}
class BMW
{
protected $luntai;
public function __construct($luntai)
{
$this->luntai = $luntai;
}
public function run()
{
$this->luntai->roll();
echo '开着宝马<hr>';
}
}
class Container
{
//存放所绑定的对象
protected static $register = [];
//绑定闭包函数
public static function bind($name, Closure $clo)
{
self::$register[$name] = $clo;
}
//创建对象函数
public static function make($name)
{
$clo = self::$register[$name];
return $clo();
}
}
Container::bind('luntai', function () {
return new Luntai();
});
Container::bind('bmw', function () {
return new BMW(Container::make('luntai'));
});
$bmw = Container::make('bmw');
return $bmw->run();//"车轮在滚动<hr>" "开着宝马<hr>"