分别使用构造方法、普通方法实现依赖注入

Original 2019-04-20 21:05:31 295
abstract:<?php /**  * 依赖注入  * Date: 2019/4/20  * Time: 20:51  */ // 创建课程类 class Course {     // 使用单利模式    &nbs
<?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));


Correcting teacher:天蓬老师Correction time:2019-04-22 09:53:25
Teacher's summary:面向对象编程的本质是通过多个对象之间的相互调用实现功能, 而对象的实例化过程, 如果在另一个对象内部完成, 会造成这个对象严重依赖另一个对象的实现, 这种现象叫耦合, 为了解决这个问题, 将对象的创建过程前移,放在对象的外部完成,再通过传参的方式注入到另一个对象内部...

Release Notes

Popular Entries