Blogger Information
Blog 8
fans 0
comment 1
visits 11404
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
trait命名冲突解决、trait中改变trait成员中的访问控制、trait与接口,抽象类混合编程
混混
Original
792 people have browsed it

1.Trait组合的同名方法的命名冲突的解决方案,以及访问的权限修改

关键字:insteadOf 替换; as 取别名或者修改权限;
实例演示:

  1. <?php
  2. trait tUser1
  3. {
  4. public function res()
  5. {
  6. return __TRAIT__.'=>'.__METHOD__;
  7. }
  8. }
  9. trait tUser2
  10. {
  11. public function res()
  12. {
  13. return __TRAIT__.'=>'.__METHOD__;
  14. }
  15. }
  16. trait tUser3
  17. {
  18. use tUser1,tUser2
  19. {
  20. tUser1::res insteadOf tUser2;//替换 tUser2 里面的res方法
  21. tUser2::res as res2;//给res 取一个别名
  22. }
  23. use tUser1{res as protected res1;}//修改tUser 方法的访问权限
  24. }
  25. class User
  26. {
  27. use tUser3;
  28. }
  29. $obj=new User();
  30. echo $obj->res();
  31. echo '<hr>';
  32. echo $obj->res2();
  33. echo '<hr>';
  34. echo $obj->res1();
  35. ?>

输出结果:

个人理解:在取别名使用前,一定要先替换,不然会报错。之前在框架中直接使用as,不知道是不是在框架中有封装 insteadOf。

2.trait与抽象类、接口混合编程

实例演示:

  1. <?php
  2. interface iUser1
  3. {
  4. const NAME='刘德华';
  5. const AGE=17;
  6. public static function res();
  7. public static function ret($age2);
  8. }
  9. trait tUser1
  10. {
  11. public static function res()
  12. {
  13. return iUser1::NAME.iUser1::AGE.'出道';
  14. }
  15. }
  16. abstract class tUser2 implements iUser1
  17. {
  18. // use tUser1;
  19. public static function ret($age2)
  20. {
  21. // $age2=24;
  22. return $age2.'获取金像奖';
  23. }
  24. }
  25. class User extends tUser2
  26. {
  27. Use tUser1;
  28. }
  29. $obj=new User();
  30. echo $obj::res();
  31. echo '<hr>';
  32. echo $obj::ret(24);
  33. ?>

输出结果:

个人总结:接口中声明方法;需要实现直接在抽象类或者trait类中实现,工作类中直接调用就好,注意引入的关系和层级

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:trait虽好,也不可滥用
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