博客列表 >PHP:Trait与接口、抽象类详解

PHP:Trait与接口、抽象类详解

暝皑祯π_π
暝皑祯π_π原创
2020年05月05日 17:16:11963浏览

trait组合使用方法

  1. <?php
  2. // trait组合使用方法
  3. // 把多个trait引用到一个trait中,然后在工作类中只需引用一个trait就可以了
  4. // trait1
  5. trait tOne
  6. {
  7. public function one()
  8. {
  9. return __TRAIT__;
  10. }
  11. }
  12. // trait2
  13. trait tTwo
  14. {
  15. public function two()
  16. {
  17. return __FUNCTION__;
  18. }
  19. }
  20. // trait3
  21. trait tThree
  22. {
  23. public function three()
  24. {
  25. return __CLASS__;
  26. }
  27. }
  28. // 3个trait的集合
  29. trait tGather
  30. {
  31. use tOne,tTwo,tThree;
  32. }
  33. // 工作类
  34. class Dd
  35. {
  36. // 引用trait的集合 ,就能调用三个trait中成员
  37. use tGather;
  38. }
  39. $a = new Dd;
  40. echo $a->three();
  41. echo '<hr>';
  42. echo $a->two();
  43. echo '<hr>';
  44. echo $a->one();
  45. echo '<hr>';

trait组合中的方法命名冲突解决方法

  1. // trait组合中的方法命名冲突解决方法
  2. // 替换
  3. // trait1
  4. trait tFout
  5. {
  6. public function one()
  7. {
  8. return __TRAIT__;
  9. }
  10. }
  11. // trait2
  12. trait tFive
  13. {
  14. public function one()
  15. {
  16. return __FUNCTION__;
  17. }
  18. }
  19. // 2个trait的集合
  20. trait tGather1
  21. {
  22. // 语法
  23. use tFout,tFive{
  24. // 替换:关键字:insteadOf
  25. tFout::one insteadOf tFive;
  26. // 别名:关键字:as
  27. tFout::one as fu;
  28. }
  29. // 访问控制符:关键字:as
  30. // 语法
  31. use tFout {one as protected one1;}
  32. }
  33. // 工作类
  34. class Db
  35. {
  36. use tGather1;
  37. }
  38. $b = new Db;
  39. echo $b->one();
  40. echo '<hr>';
  41. echo $b->fu();
  42. echo '<hr>';

trait,接口,抽象类联合编程

  1. // trait,接口,抽象类联合编程
  2. // 接口定义方法
  3. // trait实现接口中的抽象方法,打包在一起以供调用
  4. // 接口:定义抽象方法
  5. interface iA
  6. {
  7. public function bag();
  8. public function dag();
  9. }
  10. // trait:实现方法
  11. // trait可以只实现接口中一个方法
  12. trait tB
  13. {
  14. public function bag()
  15. {
  16. return __METHOD__;
  17. }
  18. }
  19. // 工作类:调用trait
  20. // 可以在其他类中调用trait,实现代码复用
  21. class C
  22. {
  23. use Tb;
  24. }
  25. $l = new C;
  26. echo $l->bag();

总结

  • trait的作用
    • 1 表明类可以做什么;
    • 2 提供模块化实现;
  • trait 实现接口方法的优点:使我们的工作类更加简洁。
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议