批改状态:合格
老师批语:
声明:
Tirait特性:
方法集合,临时类,类中类,可以嵌套到宿主类
拥有三种成员:1.常规成员,2.静态成员,3.抽象成员(没有属性)
优先级:自身方法 > trait的方法 > 继承的方法
<?php//代码复用// 在trait类中定义方法,在不同类中调用trait tDemo{public function show($name,$age,$like){printf('Hello,大家好,我叫%s,今年%s,%s。',$name,$age,$like);}}class User1{use tDemo;protected $name = '王强';protected $age = 19;protected $like ='爱打篮球';public function introduce(){return $this->show($this->name,$this->age,$this->like);}}class User2{use tDemo;protected $name = '李娟';protected $age = 20;protected $like ='爱跳舞';public function introduce(){return $this->show($this->name,$this->age,$this->like);}}class User3{use tDemo;protected $name = '兰兰';protected $age = 19;protected $like ='爱画画';public function introduce(){return $this->show($this->name,$this->age,$this->like);}}(new User1)->introduce();echo '<hr>';(new User2)->introduce();echo '<hr>';(new User3)->introduce();
输出结果:
<?php//在继承上下文中的应用trait Demo{public static function way(){return 'trait中的方法' . __METHOD__;}}// 父类/超类/基类class Father{use Demo;public static function way(){return '基类中的方法' . __METHOD__;}}// 子类/扩展类class Son extends Father{use Demo;public static function way(){return '子类中的方法' . __METHOD__;}}//子类同名成员优先级大于父级同名成员//子类>trait>父类echo son::way();
输出结果:
<?php//扩展类功能的扩展trait tDemo1{// 打印所有属性(公共方法)public function getProps(){printf('%s', print_r(get_class_vars(__CLASS__), true));}}trait tDemo2{// 打印所有方法(公共方法)public function getMethods(){printf('%s', print_r(get_class_methods(__CLASS__), true));}}trait tDemo3{use tDemo1, tDemo2;}class Demo1{use tDemo1, tDemo2; //可引用多个trait实现功能扩展protected $name = '李军';protected $gender = '男';public function show(){return $this -> getProps();}}class Demo2{use tDemo3; //tDemo3引入了tDemo1、tDemo2,此时只引入一个trait就可以protected $name = '张丹';protected $gender = '女';public function show(){return $this -> getProps();}}echo 'Demo1' . "<br>";echo '类属性:', (new Demo1)->getProps() . "<br>";echo '类方法:', (new Demo1)->getMethods();echo '<hr>';echo 'Demo2' . "<br>";echo '类属性:', (new Demo2)->getProps() . "<br>";echo '类方法:', (new Demo2)->getMethods();
输出结果:
<?php//在trait组合中命名冲突的解决方案trait Demo1{public function show(){return '我是:'.__METHOD__;}}trait Demo2{public function show(){return '我是:'.__METHOD__;}}trait Demo3{use Demo1, Demo2 {// 给Demo2::show()起个别名: tb2Demo2::show as tb2;// 调用Demo1::show()替换成Demo2::show()Demo1::show insteadOf Demo2;}}// 工作类尽可能写得代码清晰,简洁class Demo{use Demo3;}echo (new Demo)->show();echo '';// 别名访问Demo2::showecho (new Demo)->tb2();
输出结果:
<?php//trait和interface的组合// 接口interface iDemo{public static function index();}// traittrait tDemo{// 将接口中的抽象方法的实现过程放在trait中实现,并在工作类中调用public static function index(){return __METHOD__;}}// 实现类class Hello implements iDemo{use tDemo;}// 客户端echo Hello::index();
输出结果:

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