PHP以接口方式实现多重继承(完全模拟)--学习笔记

 1.UML类图:

 

 

 

 

2.PHP代码:

<?php

/**
 * Created by PhpStorm.
 * User: andy
 * Date: 16-11-23
 * Time: 下午7:57
 */
interface User
{
    function getName();
}

interface Teacher
{
    function getWorkYear();
}

class Student implements User
{
    private $name = 'lisi';

    function getName()
    {
        // TODO: Implement getName() method.
        echo 'Student name is ' . $this->name . '<br />';
    }
}

class GraduateTeacher implements Teacher
{
    private $work_year = 2;

    function getWorkYear()
    {
        // TODO: Implement getWorkYear() method.
        echo 'Teacher work year is ' . $this->work_year . '<br />';
    }
}

class GraduateStudent extends Student implements Teacher
{
    private $teacher;


    public function __construct()
    {
        $this->teacher = new GraduateTeacher();
    }

    function getWorkYear()
    {
        $this->teacher->getWorkYear();
    }
}

class Test
{
    static function getName(User $student)
    {
        $student->getName();
    }

    //当Teacher改成GraduateTeacher,到后面代码行的“Test::getWorkYear($lisi);”就会报错
    static function getWorkYear(Teacher $teacher)
    {
        $teacher->getWorkYear();
    }
}

$lisi = new GraduateStudent();
$lisi->getName();
$lisi->getWorkYear();


echo '<hr />';
Test::getName($lisi);
Test::getWorkYear($lisi); //这里不会报错,因为$lisi所属的类GraduateStudent,实现了Teacher的接口,相当于Teacher身份

 

posted @ 2016-11-25 12:08  ok_008  阅读(1264)  评论(0编辑  收藏  举报
给我写信