博主信息
博文 145
粉丝 7
评论 7
访问量 202290
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
PHP基础知识:trait的应用和案例
李东亚¹⁸⁰³⁹⁵⁴⁰¹²⁰
原创
1106人浏览过

代码练习

1、代码

  1. <?php
  2. trait A
  3. {
  4. function put(){
  5. return 'A当前类名'.__CLASS__;
  6. }
  7. }
  8. trait B
  9. {
  10. function put(){
  11. return 'B当前类名'.__CLASS__;
  12. }
  13. }
  14. trait AB
  15. {
  16. use A,B{
  17. B::put insteadOf A;//使用B中的同名方法代替A中的同名方法insteadOf;
  18. A::put as aput;//给A中的同名方法取个别名as;
  19. }
  20. public function getf(){
  21. return 'AB中调用的方法:'.__METHOD__;
  22. }
  23. }
  24. class Work
  25. {
  26. use AB{
  27. //修改trait中的方法访问控制
  28. getf as protected gf;
  29. }
  30. }
  31. echo (new Work())->put(),'<br>';
  32. echo (new Work())->aput(),'<br>';
  33. echo (new Work())->getf(),'<br>';
  34. echo (new Work())->gf(),'<br>';

2、运行结果

trait优缺点:

优点:trait类似于函数库,任何class都可以调用,可以节省代码重写率;
不适合放在父类(含接口类)或者子类中的方法可以通过trait来实现;
缺点:trait无法实列化(不像函数可以随时调用执行),只能通过实列类来执行;

案例

1、案例代码

  1. <?php
  2. // 接口
  3. interface iP
  4. {
  5. public static function getn(int $a,int $b);
  6. }
  7. // trait
  8. trait tC
  9. {
  10. public static function computer(int $a,int $b)
  11. {
  12. return "{$a}×{$b}=".($a*$b).'<br>';
  13. }
  14. }
  15. // 工作类
  16. class P implements iP
  17. {
  18. use tC;
  19. public static function getn (int $a, int $b)
  20. {
  21. $arr=range($a,$b);
  22. for($i=0;$i<count($arr);$i++){
  23. if(($i+1)<count($arr)){
  24. // 静态函数无法使用$this;但可以使用new self();
  25. echo (new self)->computer($arr[$i],$arr[$i+1]);
  26. // echo static::computer($arr[$i],$arr[$i+1]);
  27. // echo tC::computer($arr[$i],$arr[$i+1]);
  28. }
  29. }
  30. }
  31. }
  32. // 客户端
  33. echo "<style>
  34. input{
  35. height:30px;
  36. width:30px;
  37. vertical-align: middle;
  38. font-size:18px;
  39. }
  40. button{
  41. background-color:lightblue;
  42. height:30px;
  43. width:80px;
  44. }
  45. </style>";
  46. echo"<h1>自动生成<input/>-<input/>的乘法公式:</h1>";
  47. print_r(P::getn(0,5));
  48. echo "<button>生成</button>";

1、案例运行结果

总结

1、trait方法集:可以组合使用; 引用多个trait, 中间用逗号分开;
2、trait解决方法命名冲突的方法:

  1. 替代:关键字`insteadOf`
  2. 别名:关键字`as`
  3. 别名可以改变成员访问控制:遵循public>protected>private

3、使用trait时,用关键字use

批改老师:天蓬老师天蓬老师

批改状态:合格

老师批语:trait, 就像是你们单位招的临时工, 活都是他们干的, 但并得不到类中原生成员的身份, 出事了, trait还能顶包: 这是第三方类库有Bug...
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
1条评论
李**¹⁸⁰³⁹⁵⁴⁰¹²⁰ 2020-05-06 18:21:15
通过别名的方法(use name{ func as public F;})改变trait 中的访问限制,可以在public、protected、private三者之间随意切换;
1楼
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学