Correction status:qualified
Teacher's comments:
class Spring { public function flower() { return '春天花会开'; } public function bird() { return '鸟儿自由自在'; } } //依赖注入:把当前依赖的对象当做参数注入到当前的类中,简称依赖注入 //构造方法依赖注入 class Season1 { private $spring; public function __construct(Spring $spring) { return $this->spring=$spring; } public function getSeason() { return '我们喜欢春的美,因为:'.$this->spring->flower().','.$this->spring->bird(); } } $spring = new Spring(); $season1 = new Season1($spring); echo $season1->getSeason(); echo '<hr>'; //普通方法依赖注入 class season2 { public function getSeason(Spring $spring) { return '我们喜欢春的美,因为:'.$spring->flower().','.$spring->bird(); } } $spring = new Spring(); $season2 = new Season2(); echo $season2->getSeason($spring);
点击 "运行实例" 按钮查看在线实例