Blogger Information
Blog 29
fans 0
comment 0
visits 27003
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP基础:trait方法命名冲突解决方案及修改访问控制
暴宇
Original
1202 people have browsed it

PHP基础:trait方法命名冲突解决方案及修改访问控制

1.trait组合的同名方法命名冲突的解决方案

1.1指定默认执行(替代方式)
1.2给不同的组件方法起别名

  1. // 组件1
  2. trait t1
  3. {
  4. public function tfun()
  5. {
  6. return __TRAIT__ . ' 组件中的方法 ' . __METHOD__;
  7. }
  8. }
  9. // 组件2
  10. trait t2
  11. {
  12. public function tfun()
  13. {
  14. return __TRAIT__ . ' 组件中的方法 ' . __METHOD__;
  15. }
  16. }
  17. // 组件3(引入组件1和组件2)
  18. // 利用指定默认执行方法和别名的方式解决命名冲突
  19. trait t3
  20. {
  21. use t1, t2 {
  22. // 1. 替代(指定默认执行t1组件中的tfun方法,也可理解为用t1组件中的方法替代t2组件中的同名方法)
  23. t1::tfun insteadOf t2;
  24. // 2. 别名
  25. t2::tfun as td2;
  26. }
  27. }
  28. class jobClass{
  29. use t3;
  30. }
  31. $job=new jobClass;
  32. echo $job->tfun(),'<hr>';
  33. echo $job->td2(),'<hr>';

2.修改trait方法的访问控制

用as关键字修改trait方法的访问控制

  1. trait t4{
  2. // as: 还可以修改trait成员的访问控制
  3. use t1 {tfun as private td1;}
  4. }
  5. class jobClass{
  6. use t4;
  7. }
  8. $job=new jobClass;
  9. // echo $job->td1(),'<hr>';

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:一二阶段作业,请在6月10日前完成
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!