分别使用构造方法、普通方法实现依赖注入
<?php
/**
* 依赖注入
* Date: 2019/4/20
* Time: 20:51
*/
// 创建课程类
class Course
{
// 使用单利模式
protected static $instance = null;
private function __construct(){}
private function __clone(){}
public static function instance()
{
if(is_null(static::$instance))
{
static::$instance = new static;
}
return static::$instance;
}
// PHP 课程
public function php(){
return 'PHP';
}
// 课程 Mysql
public function Mysql()
{
return 'Mysql';
}
}
// 创建学生类 使用构造方法实现依赖主入
class Student
{
private $course = null;
public function __construct(Course $course)
{
$this->course = $course;
}
public function MyCourse()
{
return '我学习了'.$this->course->php().'课程';
}
}
// 实例化 课程类
$course = Course::instance();
// 实例化学生类
$student = new Student($course);
// 输出
print_r($student->MyCourse());
echo '<hr/>';
// 使用普通方法实现依赖注入
class Students
{
// 使用普通方法实现依赖注入
public function MyCourse(Course $course)
{
return '我学习了'.$course->Mysql().'课程';
}
}
// 实例化普通方法的学生类
$student1 = new Students();
print_r($student1->MyCourse($course));