PHP以接口方式實現多重繼承(徹底模擬)--學習筆記

 1.UML類圖:php

 

 

 

 

2.PHP代碼:this

<?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身份
相關文章
相關標籤/搜索