批改状态:合格
老师批语:
trait可以使多个无关的类共用同一种方法或属性trait无法实例化,在类中使用use关键字引用
<?phptrait tSum{public function sum($a, $b){return $a + $b;}}class countNum{use tSum;}class totalPrice{use tSum;}echo (new countNum)->sum(10, 20),'<br>';echo (new totalPrice)->sum(3, 20),'<br>';

<?phptrait tRet{public static function ret(){return 'trait';}}class cFRet{use tRet;public static function ret(){return '父类';}}class cSRet extends cFRet{use tRet;public static function ret(){return '子类';}}//此时浏览器上输出子类 可以看出 子类优先级要高于父类与`trait`//当在子类中注释掉成员方法之后 浏览器上输出trait 可以看出 trait的优先级要高于父类//当在子类中注释掉use trait之后 浏览器上输出子类 可以看出 类优先级要高于父类echo cSRet::ret(),'<br>';

trait 说明trait优先级比父类高
trait与父类的同名方法时
<?phptrait tRet1{public static function ret1(){return '你好';}}trait tRet2{public static function ret2(){return 'php';}}trait tRet{ //组合两个traituse tRet1, tRet2;}class cRet{use tRet; //use tRet1, tRet2;}echo cRet::ret1().':'.cRet::ret2();

as给其中一个同名方法起个别名insteadOf来明确指定使用冲突方法中的哪一个
<?phptrait hello{public function hw(){return 'hello';}}trait world{public function hw(){return 'world';}}class hello_wrold{use hello, world{hello::hw as hello;world::hw insteadOf hello;}}echo (new hello_wrold)->hw(),'<br>';//使用别名访问echo (new hello_wrold)->hello();
<?php//声明一个接口定义helloWorld方法interface iHelloWorld{public function helloWorld();}//声明一个triat 实现helloWorld方法trait tHelloWorld{public function helloWorld(){return 'Hello World';}}//声明一个工作类 实现接口 使用traitclass cHelloWorld implements iHelloWorld{use tHelloWorld;}echo (new cHelloWorld)->helloWorld();

trait是通过代码复用来实现具体功能扩展interface是通过代码声明一些特定功能,没有具体的实现内容trait或者多个interface,但只能继承一个抽象类
<?php//声明一个接口 特定行为:握手interface iAction{public function shakeHands();}//声明一个trait 实现握手行为trait tShakeHands{public function shakeHands(){return true;}}//声明一个抽象类 狗类:吠、摇尾巴abstract class aDogs{abstract public function bark();abstract public function wagTail();}//实现类 实现一只狗的基本属性行为class Dog extends aDogs implements iAction{use tShakeHands;public function bark(){return true;}public function wagTail(){return true;}}//输出$myDog = new Dog();echo 'my dog '.($myDog->bark()?'can':'cannot').' bark<br>';echo 'my dog '.($myDog->wagTail()?'can':'cannot').' wagging its tail<br>';echo 'my dog '.($myDog->shakeHands()?'can':'cannot').' shake hands';

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号