Blogger Information
Blog 26
fans 0
comment 0
visits 18148
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
接口与trait的基础
雪~人胖胖
Original
701 people have browsed it

接口

  1. //多接口继承
  2. interface iComputer1
  3. {
  4. public function version();
  5. }
  6. interface iComputer2
  7. {
  8. const str1 = '运行win7';
  9. }
  10. interface iComputer extends iComputer1,iComputer2
  11. {
  12. public function work();
  13. }
  14. //抽象类不用全部实现接口方法
  15. abstract class Note1 implements iComputer
  16. {
  17. public function version()
  18. {
  19. echo '笔记本';
  20. }
  21. }
  22. class Note extends Note1
  23. {
  24. public function work(){
  25. echo self::str1;
  26. }
  27. }
  28. //普通类必须全部实现接口方法
  29. class Desk implements iComputer
  30. {
  31. public function version(){
  32. echo '台式机';
  33. }
  34. public function work()
  35. {
  36. echo '运行win10';
  37. }
  38. }
  39. class Run
  40. {
  41. public static function sec($type)
  42. {
  43. $type->version();
  44. $type->work();
  45. }
  46. }
  47. $note = new Note();
  48. $desk = new Desk();
  49. $run = Run::sec($note);

效果图

Trait

  1. <?php
  2. //trait:与抽象类,接口一样不能实例化,只能嵌入到宿主类中使用
  3. //trait是一个特殊类:1:常规或静态属性方法2:抽象属性方法 但是不能用类常量
  4. trait tDemo
  5. {
  6. public static $name = '张三';
  7. public static $sex = '男';
  8. public $age;
  9. public static function getName()
  10. {
  11. echo self::$name;
  12. }
  13. }
  14. class Dad
  15. {
  16. public static $name1 = 'Tom';
  17. public static function getName()
  18. {
  19. echo self::$name1;
  20. }
  21. }
  22. //属性不能重名 否则报错
  23. //能实现代码的复用
  24. //子类中use trait 当继承的父类方法重名时 trait的优先级大于父类
  25. //优先级顺序 子类>trait>父类
  26. class Son extends Dad
  27. {
  28. use tDemo;
  29. }
  30. Son::getName();
  31. echo Son::$sex;

图例

总结

有点难,脑子不够用,只能想点简单的例子,需要多看看视频消化一下

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:其实这些案例看是简单的了, 还是要多动脑动手呀
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!