Maison > php教程 > php手册 > le corps du texte

php使用接口(interface)实现多重继承

WBOY
Libérer: 2016-06-06 19:55:36
original
1299 Les gens l'ont consulté

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 php中使用接口(interface)实现多重继承: 我们都知道PHP中的类(class)是单继承的,那是不是就没有办法实现多重继承了呢?答案是否定的.我们可以通过其它特殊的方式实现类的多重继承,比如使用接口(interf

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

    php中使用接口(interface)实现多重继承:

    我们都知道PHP中的类(class)是单继承的,那是不是就没有办法实现多重继承了呢?答案是否定的.我们可以通过其它特殊的方式实现类的多重继承,比如使用接口(interface)实现,只要把类的特征抽象为接口,并通过实现接口的方式让对象有多重身份,通过这样就可以模拟多重继承了.

    下面是一个用接口(interface)实现多重继承的例子,源代码如下:

   

    interface UserInterface{ //定义User的接口

    function getname();

    }

    interface TeacherInterface{ //teacher相关接口

    function getLengthOfService();

    }

    class User implements UserInterface { //实现UserInterface接口

    private $name = “tom”;

    public function getName(){

    return $this->name;

    }

    }

    class Teacher implements TeacherInterface { //实现TeacherInterface接口

    private $lengthOfService = 5; // 工龄

    public function getLengthOfService(){

    return $this->lengthOfService;

    }

    }

    // 继承自User类,同时实现了TeacherInterface接口.

    class GraduateStudent extends User implements TeacherInterface {

    private $teacher ;

    public function __construct(){

    $this->teacher = new Teacher();

    }

    public function getLengthOfService(){

    return $this->teacher->getLengthOfService();

    }

    }

    class Act{

    //注意这里的类型提示改成了接口类型

    public static function getUserName(UserInterface $_user){

    echo “Name is ” . $_user->getName() .“
”;

    }

    //这里的类型提示改成了TeacherInterface类型.

    public static function getLengthOfService(TeacherInterface $_teacher){

    echo “Age is ” .$_teacher->getLengthOfService() .“
”;

    }

    }

    $graduateStudent = new GraduateStudent();

    Act::getUserName($graduateStudent);

    Act::getLengthOfService($graduateStudent);

    //结果正如我们所要的,实现了有多重身份的一个对象.

    ?>

    示例运行结果如下:

    Name is tom

    Age is 5

php使用接口(interface)实现多重继承

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Recommandations populaires
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!