Blogger Information
Blog 26
fans 0
comment 0
visits 18142
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Trait组合
雪~人胖胖
Original
753 people have browsed it

Trait组合的同名方法的命名冲突的解决方案

  1. trait tBase1
  2. {
  3. protected static $name;
  4. public function display()
  5. {
  6. return __TRAIT__;
  7. }
  8. }
  9. trait tBase2
  10. {
  11. protected static $price;
  12. public function display()
  13. {
  14. return __TRAIT__;
  15. }
  16. }
  17. trait tBase
  18. {
  19. use tBase1,tBase2{
  20. //1.当trait中方法重名时可以替换
  21. tBase1::display insteadOf tBase2;
  22. //2.给方法取别名
  23. tBase2::display as td2;
  24. }
  25. //as还能改访问限制
  26. use tBase1 {display as protected;}
  27. }
  28. class Product
  29. {
  30. use tBase;
  31. public static function write($name,$price)
  32. {
  33. echo self::$name= $name .'的价格是:'.self::$price=$price.__METHOD__;
  34. }
  35. public static function fatch($name,$price)
  36. {
  37. return static::write($name,$price);
  38. }
  39. }
  40. class Base extends Product
  41. {
  42. public static function write($name,$price)
  43. {
  44. echo self::$name= $name .'优惠后的价格是:'.self::$price=$price.__METHOD__;
  45. }
  46. }
  47. Base::fatch('手机',8888);
  48. $product = new Product;
  49. echo $product->display();

图例

$trait 实现 接口方法的优点
1.可以更方便的应用在工作类当中
2.客户端代码越简洁越好 容易维护

小抽奖

  1. interface iReward
  2. {
  3. public function getReward($total);
  4. }
  5. trait tReward
  6. {
  7. public function getReward($total)
  8. {
  9. $win1 = floor((0.12*$total)/100);
  10. $win2 = floor((1*$total)/100);
  11. $win3 = floor((2*$total)/100);
  12. $other = $total-$win1-$win2-$win3;
  13. $return = [];
  14. for ($i=0;$i<$win1;$i++)
  15. {
  16. $return[] = 1;
  17. }
  18. for ($j=0;$j<$win2;$j++)
  19. {
  20. $return[] = 2;
  21. }
  22. for ($m=0;$m<$win3;$m++)
  23. {
  24. $return[] = 3;
  25. }
  26. for ($n=0;$n<$other;$n++)
  27. {
  28. $return[] = '谢谢惠顾';
  29. }
  30. shuffle($return);
  31. return $return[array_rand($return)];
  32. }
  33. }
  34. class Reward implements iReward{
  35. use tReward;
  36. }
  37. $reward =new Reward;
  38. echo $reward->getReward(1000);

总结

这节课学习了trait的组合命名冲突的2种解决方法,as的用法,以及接口与trait的实战,发现自己的数组函数基础很不好,需要多复习。

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
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!