本文实例讲述了PHP Trait功能与用法。分享给大家供大家参考,具体如下:
Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。
1.如果引入的Trait有同名的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
trait A{ public function eat(){ echo 'A-eat' ; } public function say(){ echo 'A-say' ; } } trait B{ public function eat(){ echo 'B-eat' ; } public function say(){ echo 'B-say' ; } } class People{ use A,B{ A::eat insteadof B; B::eat as eatbak; B::say insteadof A; } } $people = new People(); $people ->eat(); echo "<br/>" ; $people ->say(); echo "<br/>" ; $people ->eatbak(); |
运行结果:
A-eat
B-say
B-eat
2.修改访问控制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<?php trait Test { public function say() { echo 'say hello' ; } } class People { use Test { say as protected ; } } $people = new People(); $people ->say(); |
运行结果:
Fatal error: Call to protected method People::say() from context '' in D:\phpdemo\trait_Demo.php on line 14
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://blog.csdn.net/huangyuxin_/article/details/84885115