返回分别使用构造方......登陆

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

JasonKim2019-04-20 21:05:31295
<?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));


最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送