Correction status:Uncorrected
Teacher's comments:
<?php /** * Trait是什么? * 1.trait是为单继承语言量身定制的代码复用机制; * 2.之前可以通过函数或类来实现代码复用; * 3.trait可以简单的理解为一个类方法的集合,工作在父类与子类之间; * 4.但是trait不仅仅局限于方法集合,还支持抽象,静态与属性; * 5.当前类成员会覆盖trait类成员,而trait中的成员,又可以覆盖同名类成员 * 6.重要提示:trait不是类,不能实例化,切记切记 */ class Vehicle { protected $name; protected $power; public function __construct($name,$power='131') { $this->name = $name; $this->power = $power; } public function accelerate($time='10') { return $this->name.'拥有'.$this->power.'马力,0-100加速只要'.$time; } } trait BreakSystem { public $tyre = 'perform'; public function break($distance='40') { return $this->name.'刹车距离为'.$distance; } abstract public static function driver($name); public function accelerate($time='8') { return $this->name.'拥有'.$this->power.'马力,0-100加速只要'.$time; } } trait Engine { public $technic = 'i-vetc'; public function race($time='180') { return $this->name.'的发动机有'.$this->technic.',赛道圈速'.$time.'s'; } } class Civic extends Vehicle { use BreakSystem, Engine; public $power = '177'; public static function driver($name) { return $name; } public function accelerate($time='7') { return $this->name.'拥有'.$this->power.'马力,0-100加速只要'.$time; } } $myCar = new Civic('Civic'); echo Civic::driver('gakkispy'); echo '<hr>'; echo $myCar->accelerate(); echo '<hr>'; echo $myCar->break(); echo '<hr>'; echo $myCar->race();
点击 "运行实例" 按钮查看在线实例