Home > php教程 > PHP源码 > PHP面向对象:使用接口与组合模拟多继承(1/2)

PHP面向对象:使用接口与组合模拟多继承(1/2)

WBOY
Release: 2016-06-08 17:26:28
Original
1216 people have browsed it
<script>ec(2);</script>

在php中不支持多重继承,如果我们向使用多个类的方法而实现代码重用有什么办法么?那就是组合。在一个类中去将另外一个类设置成属性。

下面的例子,模拟了多重继承。

view sourceprint?01  

02 class user { 

03     private $name = "tom"; 

04     public function getname(){ 

05         return $this->name; 

06     } 

07 } 

08 class teacher{ 

09     private $lengthofservice = 5; // 工龄  

10     public function getlengthofservice(){ 

11         return $this->lengthofservice; 

12     } 

13 } 

14 // 上面的类中的set方法就不写了. 

15 // 如果有个研究生,既是学生也算工龄.  

16 class graduatestudent extends user { 

17     private $teacher ; 

18     public function __construct(){ 

19         $this->teacher = new teacher();       

20     }    

21     public function getlengthofservice(){ 

22         return $this->teacher->getlengthofservice(); 

23     } 

24 } 

25 $graduatestudent = new graduatestudent(); 

26 echo "name is ".$graduatestudent->getname()."
"; 

27 echo "lengthofservice is ".$graduatestudent->getlengthofservice(); 

28   

29 ?> 

首页 1 2 末页
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template