Blogger Information
Blog 13
fans 0
comment 7
visits 17265
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实例 演示 trait 的功能和优先级
ccc9112020
Original
608 people have browsed it

trait可以实现代码复用和实现扩展功能。另外需要注意trait命名冲突的解决方案,还有trait可以和interface结合使用。以下简单演示。

  1. // trait功能1:实现代码复用,并演示优先级
  2. trait show{
  3. public static function getAge(){
  4. return __METHOD__;
  5. }
  6. }
  7. class One{
  8. public static function getAge(){
  9. return __METHOD__;
  10. }
  11. }
  12. class Two extends One{
  13. use show;
  14. public static function getAge()
  15. {
  16. return __METHOD__;
  17. }
  18. }
  19. // 优先级:子类>trait>父类
  20. // 可以分别注释子类,trait的方法查看输出结果,就可以得到优先级
  21. echo (new Two())->getAge();
  1. /**
  2. *
  3. * trait功能2:实现扩展功能,并演示trait成员方法命名冲突
  4. *
  5. */
  6. trait tDemo1{
  7. public function display()
  8. {
  9. return __METHOD__;
  10. }
  11. public function getProps()
  12. {
  13. printf('<pre>%s</pre>',print_r(get_class_vars(__CLASS__),true));
  14. }
  15. }
  16. trait tDemo2{
  17. public function display()
  18. {
  19. return __METHOD__;
  20. }
  21. public function getMethods()
  22. {
  23. printf('<pre>%s</pre>',print_r(get_class_methods(__CLASS__),true));
  24. }
  25. }
  26. trait tDemo3{
  27. // use tDemo1,tDemo2;
  28. // 解决命名冲突
  29. use tDemo1,tDemo2{
  30. tDemo2::display as td2;
  31. // 以下错误
  32. // tDemo1::display as td1;
  33. tDemo1::display insteadof tDemo2;
  34. }
  35. }
  36. class Work1{
  37. use tDemo3;
  38. public $name='西瓜';
  39. public $price=2;
  40. public function getInfo()
  41. {
  42. return $this->name.":".$this->price;
  43. }
  44. }
  45. echo (new Work1())->getInfo();
  46. (new Work1())->getProps();
  47. (new Work1())->getMethods();
  1. namespace demo4;
  2. // trait和interface组合
  3. interface iDemo{
  4. public static function index();
  5. }
  6. trait tDemo{
  7. // 把接口中的抽象方法交给Interface实现
  8. public static function index()
  9. {
  10. return __METHOD__;
  11. }
  12. }
  13. class Hello implements iDemo{
  14. use tDemo;
  15. }
  16. //
  17. $obj=new Hello;
  18. echo $obj->index();
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
1 comments
灭绝师太 2020-12-07 17:38:57
如果trait同名成员优先大于父类同名成员,可以只在trait和父类中声明两个同名成员方法,然后在子类中引用trait, 继承父类,使用子类去调用trait和父类中声明的同名成员方法,可以试一下~
1 floor
Author's latest blog post