批改状态:合格
老师批语:合格,写的不错
trait可以实现代码复用和实现扩展功能。另外需要注意trait命名冲突的解决方案,还有trait可以和interface结合使用。以下简单演示。
// trait功能1:实现代码复用,并演示优先级trait show{public static function getAge(){return __METHOD__;}}class One{public static function getAge(){return __METHOD__;}}class Two extends One{use show;public static function getAge(){return __METHOD__;}}// 优先级:子类>trait>父类// 可以分别注释子类,trait的方法查看输出结果,就可以得到优先级echo (new Two())->getAge();
/**** trait功能2:实现扩展功能,并演示trait成员方法命名冲突**/trait tDemo1{public function display(){return __METHOD__;}public function getProps(){printf('<pre>%s</pre>',print_r(get_class_vars(__CLASS__),true));}}trait tDemo2{public function display(){return __METHOD__;}public function getMethods(){printf('<pre>%s</pre>',print_r(get_class_methods(__CLASS__),true));}}trait tDemo3{// use tDemo1,tDemo2;// 解决命名冲突use tDemo1,tDemo2{tDemo2::display as td2;// 以下错误// tDemo1::display as td1;tDemo1::display insteadof tDemo2;}}class Work1{use tDemo3;public $name='西瓜';public $price=2;public function getInfo(){return $this->name.":".$this->price;}}echo (new Work1())->getInfo();(new Work1())->getProps();(new Work1())->getMethods();
namespace demo4;// trait和interface组合interface iDemo{public static function index();}trait tDemo{// 把接口中的抽象方法交给Interface实现public static function index(){return __METHOD__;}}class Hello implements iDemo{use tDemo;}//$obj=new Hello;echo $obj->index();
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号