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

php实现多重继承实例

WBOY
Libérer: 2016-06-21 08:49:11
original
2329 Les gens l'ont consulté

最近一做php开发的朋友问了一个关于php多重继承的问题,两个人说了半天,其实自己也没有搞懂什么是多重继承,今天有空,特意将多重继承这个概念给详细的了解了一下,也来谈谈在php中实现多重继承的一些看法。

说多重继承之前首先说下与其相对的单一继承,单一继承指的是一个类只可以继承自一个父类,从现实生活中举例就是说一个儿子只有一个父亲。那么多重继承就好理解了,多重继承指的是一个类可以同时从多于一个父类继承行为与特征的功能。这个有逆常理,即一个儿子可以有多个父亲。由于多重继承是面向对象编程语言中所特有的特性,所以在php5之前是没有什么继承这一说了。但在php中,即使php5也只是实现了单继承。但是我们可以通过其它特殊的方式实现类的多重继承,比如使用接口(interface),只要把类的特征抽象为接口,并通过实现接口的方式让对象有多重身份,通过这样就可以在php中模拟多重继承了。

下面通过一个实例来说明一下如何在php中实现多重继承,具体代码如下:

<?php interface UserInterface{ //定义User的接口
	function getname();
}

interface TeacherInterface{ //teacher相关接口
	function getLengthOfService();
}

class User implements UserInterface{ //实现UserInterface接口
	private $;
	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() ."<br>";
	}
	//这里的类型提示改成了TeacherInterface类型.
	public static function getLengthOfService(TeacherInterface $_teacher){
		echo "Age is " .$_teacher->getLengthOfService() ."<br>";
	}
}

$graduateStudent=new GraduateStudent();
Act::getUserName($graduateStudent);
Act::getLengthOfService($graduateStudent);
//结果正如我们所要的,实现了有多重身份的一个对象
Copier après la connexion

示例运行结果如下:

Name is tom

Age is 5

另外不得不说明的一下是多重继承在实际开发中会增加程式的复杂性与含糊性,非常不利于代码的调试。所以在开发中能够想办法用单继承的来实现的东西最好避免使用多重继承。



É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!