批改状态:合格
老师批语:下次写完一起提交
如果两个 trait 都插入一个同名的方法,没有明确解决会产生一个致使错误。解决方案有如下两种:
insteadof 操作符来明确使用哪一个 trait 中的方法(此方法会排除其他方法);as 操作符为某个方法起个别名。代码示例:
trait A {public static function say() {echo '我是 trait A say() 方法<br>';}}trait B {public static function say() {echo '我是 trait B say() 方法<br>';}}class Talk {use A, B {// 指明使用 trait A 方法A::say insteadof B;// trait b 中的 say 方法取别名 sB::say as s;}}Talk::say();Talk::s();
输出结果:
我是 trait A say() 方法我是 trait B say() 方法
使用 as 语法可以调整方法的访问控制
trait ComputerTrait{private static function shutDown() {echo '已关机';}}class Computer{use ComputerTrait {// 将 shutDown 方法访问控制设置为 publicshutDown as public;}}Computer::shutDown();
输出结果:
已关机
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号