Home  >  Article  >  Backend Development  >  【转】PHP透过接口实现多重继承

【转】PHP透过接口实现多重继承

WBOY
WBOYOriginal
2016-06-13 11:03:31755browse

【转】PHP通过接口实现多重继承

PHP类虽然是单继承的,但是可以通过其它特殊的方式实现多重继承,比如使用接口实现,只要把类的特征抽象为接口,并通过实现接口的方式让对象有多重身 份,通过这样就可以模拟多重继承了。


下面就是一个用接口模拟多重继承的例子,源代码如下:

  1. ?
  2. interface?UserInterface{?// 定义User的接口 ?
  3. ?function?getname(); ?
  4. } ?
  5. interface?TeacherInterface{?//teacher 相关接口 ?
  6. ?function?getLengthOfService(); ?
  7. } ?
  8. class?User?implements?UserInterface?{?// 实现UserInterface接口 ?
  9. ?private?$name?=?"tom"; ?
  10. ?public?function?getName(){ ?
  11. ??return?$this->name; ?
  12. ?} ?
  13. } ?
  14. class?Teacher?implements?TeacherInterface?{?// 实现TeacherInterface接口 ?
  15. ?private?$lengthOfService?=?5;?//?工 龄? ?
  16. ?public?function?getLengthOfService(){ ?
  17. ??return?$this->lengthOfService; ?
  18. ?} ?
  19. } ?
  20. //?继承自User类,同时实现了 TeacherInterface接口. ?
  21. class?GraduateStudent?extends?User?implements?TeacherInterface?{ ?
  22. ?private?$teacher?; ?
  23. ?public?function?__construct(){ ?
  24. ??$this->teacher?=?new?Teacher();?? ?
  25. ?}? ?
  26. ?public?function?getLengthOfService(){ ?
  27. ??return?$this->teacher->getLengthOfService(); ?
  28. ?} ?
  29. } ?
  30. class?Act{ ?
  31. ?//注意这里的类型提示改成了接口类型 ?
  32. ?public?static?function?getUserName(UserInterface?$_user){ ?
  33. ??echo?"Name?is?"?.?$_user->getName()?."
    "; ?
  34. ?} ?
  35. ?//这里的类型提示改成了 TeacherInterface类型. ?
  36. ?public?static?function??getLengthOfService(TeacherInterface?$_teacher){ ?
  37. ??echo?"Age?is?"?.$_teacher->getLengthOfService()?."
    "; ?
  38. ?} ?
  39. } ?
  40. $graduateStudent?=?new?GraduateStudent(); ?
  41. Act::getUserName($graduateStudent); ?
  42. Act::getLengthOfService($graduateStudent); ?
  43. //结果正如我们所要的,实现了有多重身份的一个对象. ?
  44. ?>?


示例运行结果如下:

Name is tom

Age is 5

Statement:
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