abstract://构造函数实现依赖注入class Boy1{ private $girl = null; public function __construct(Girl $girl) { $this->girl = $girl; }
//构造函数实现依赖注入
class Boy1
{
private $girl = null;
public function __construct(Girl $girl)
{
$this->girl = $girl;
}
public function getInfo()
{
return "我的女朋友".$this->girl->work();
}
}
//类外实例化Girl;
$girl = new Girl;
$boy1 = new Boy1($girl);
echo $boy1->getInfo();
echo "
";
//普通方法注入
class Boy2
{
public function buy(Girl $girl)
{
return "我的女朋友".$girl->hobby();
}
}
$girl = new Girl;
$boy2 = new Boy2;
echo $boy2->buy($girl);
在类外部实例化优势 减少类与类之间耦合性
Correcting teacher:天蓬老师Correction time:2019-05-28 15:52:29
Teacher's summary:依赖注入的重点在于外部对象的实例化的时机, 理解了这个就好了