PHP Trait功能与用法实例分析
本文实例讲述了PHP Trait功能与用法。分享给大家供大家参考,具体如下:
Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。
1.如果引入的Trait有同名的方法
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.修改访问控制
<?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相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
相关推荐
zyyjay 2020-11-09
xuebingnan 2020-11-05
samtrue 2020-11-22
stefan0 2020-11-22
yifangs 2020-10-13
songshijiazuaa 2020-09-24
hebiwtc 2020-09-18
天步 2020-09-17
83911535 2020-11-13
whatsyourname 2020-11-13
zhouyuqi 2020-11-10
Noneyes 2020-11-10
mathchao 2020-10-28
王志龙 2020-10-28
wwwsurfphpseocom 2020-10-28
diskingchuan 2020-10-23
savorTheFlavor 2020-10-23