当前位置:Gxlcms > PHP教程 > PHP中关于trait使用方法的详细介绍

PHP中关于trait使用方法的详细介绍

时间:2021-07-01 10:21:17 帮助过:25人阅读

本篇文章主要介绍了PHP中trait使用方法,个人觉得挺不错的,现在分享给大家,也给大家做个参考。一起过来看看吧。下面开始正文。

说通俗点,PHP中使用trait关键字是为了解决一个类既想集成基类的属性和方法,又想拥有别的基类的方法,而trait一般情况下是和use搭配使用的。请看下面的示例代码

  1. <?php
  2. header("Content-type:text/html;charset=utf-8");
  3. trait Drive { //使用trait 创建一个基类
  4. public $carName = 'trait'; //定义一个变量
  5. public function driving() { //定义一个方法
  6. echo "driving {$this->carName}<br>";
  7. }
  8. }
  9. class Person { //创建一个基类
  10. public function eat() { //定义一个方法
  11. echo "eat<br>";
  12. }
  13. }
  14. class Student extends Person { //创建一个子类继承Person类
  15. use Drive; //使用trait定义的类Drive
  16. public function study() { //定义一个方法
  17. echo "study<br>";
  18. }
  19. }
  20. $student = new Student(); //创建对象
  21. $student->study(); //调用自己定义的方法
  22. $student->eat(); //调用父类方法
  23. $student->driving(); //调用trait定义的类Drive的方法
  24. ?>

运行效果图如图所示

1.png

上面的例子中,Student类通过继承Person,有了eat方法,通过组合Drive,有了driving方法和属性carName。

如果Trait基类本类中都存在某个同名的属性或者方法,最终会保留哪一个呢?

  1. <?php
  2. header("Content-type:text/html;charset=utf-8");
  3. trait Drive { //使用trait定义一个类
  4. public function hello() { //定义一个方法
  5. echo "我是trait类的方法hello()<br>";
  6. }
  7. public function driving() {
  8. echo "我是trait类的方法driving()<br>"; //定义一个方法
  9. }
  10. }
  11. class Person { //创建父类
  12. public function hello() { //定义一个方法
  13. echo "我是父类的方法hello()<br>";
  14. }
  15. public function driving() { //定义一个方法
  16. echo "我是父类的方法driving()<br>";
  17. }
  18. }
  19. class Student extends Person { //创建子类继承Person类
  20. use Drive; //使用trait定义的类Drive
  21. public function hello() { //定义一个方法
  22. echo "我是子类的方法hello()<br>";
  23. }
  24. }
  25. $student = new Student(); //创建对象
  26. $student->hello(); //调用hello方法
  27. $student->driving(); //调用deiving方法
  28. ?>

运行效果如图所示

1.png因此得出结论:当方法或属性同名时,当前类中的方法会覆盖 trait的 方法,在这个例子中也就是student的hello()方法覆盖了trait中的hello()方法。而 trait 的方法又覆盖了基类中的方法。在这个例子中,trait的driving()方法就是覆盖了Person类中driving()方法。

如果想了解更多php的相关知识可以到网站的php模块中去学习更多有意思的知识。

以上就是PHP中关于trait使用方法的详细介绍的详细内容,更多请关注Gxlcms其它相关文章!

人气教程排行