将有依赖关系的类 以参数的形式注入。

原创 2018-12-14 21:54:42 186
摘要:<?php //构造方法 依赖注入 class Student { public function study() { return "好好学习天天向上"; } public function game() { return "经常玩游戏"; } }
<?php
//构造方法 依赖注入
class Student
{
	public function study()
	{
		return "好好学习天天向上";
	}

	public function game()
	{
		return "经常玩游戏";
	}
}

class Teacher
{

	private $student = null;

	public function __construct(Student $student)
	{
		$this->student = $student; 
	}
	public function getInfo()
	{
		return "学生应该".$this->student->study();
	}
}

$student = new Student;
$teacher = new Teacher($student);
echo $teacher->getInfo();
echo "<br>";
//普通方法的依赖注入
class Boy
{	public function play(Student $student)
	{
		return "男孩子".$student->game();
	}
}

$student = new Student;
$boy = new  Boy();
echo $boy->play($student); 

?>

在代码中,依赖注入的方式可以更好的解决类与类之间的相互依赖关系。

批改老师:查无此人批改时间:2018-12-15 09:43:07
老师总结:写的不错。依赖注入还有很多高级的功能,也可以去学习。加油

发布手记

热门词条