PHP Trait功能与用法实例分析

本文实例讲述了PHP Trait功能与用法,分享给大家供大家参考,具体如下:

Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。

1.如果引入的Trait有同名的方法

  1. trait A{
  2. public function eat(){
  3. echo 'A-eat';
  4. }
  5. public function say(){
  6. echo 'A-say';
  7. }
  8. }
  9. trait B{
  10. public function eat(){
  11. echo 'B-eat';
  12. }
  13. public function say(){
  14. echo 'B-say';
  15. }
  16. }
  17. class People{
  18. use A,B{
  19. A::eat insteadof B;
  20. B::eat as eatbak;
  21. B::say insteadof A;
  22. }
  23. }
  24. $people = new People();
  25. $people->eat();
  26. echo "<br/>";
  27. $people->say();
  28. echo "<br/>";
  29. $people->eatbak();

运行结果:

A-eat

B-say

B-eat

2.修改访问控制

  1. <?php
  2. trait Test {
  3. public function say() {
  4. echo 'say hello';
  5. }
  6. }
  7. class People {
  8. use Test { say as protected; }
  9. }
  10. $people = new People();
  11. $people->say();

运行结果:

Fatal error: Call to protected method People::say() from context '' in D:\phpdemo\trait_Demo.php on line 14