Correction status:qualified
Teacher's comments:
实例 <?php if (!class_exists('Person')) { class Person { protected $name; public function __construct($name='隔壁老王') { $this->name = $name; } public function study($hobby='打麻将') { return $this->name.'在学习'.$hobby; } } } if(!trait_exists('Hobby')){ trait Hobby { public $friend='小华'; public function sport($name='踢足球') { return $this->name.'和'.$this->friend.'在'.$name; } // abstract public static function hobby($name); public function study($hobby='唱歌') { return $this->name.'在学习'.$hobby; } } } if(!trait_exists('Recreation')){ trait Recreation { //这个trait类中也声明一个与Course中同名的方法sport //注意: 属性$friend不允许与Course::sport()同名 //因为目前trait中还没有处理同名属性的机制,期待新版本会解决 //这里我们将$friend 修改为 $friend1 public $friend1='小军'; public function sport($name='打蓝球') { // return $this->name.'在学习'.$name; //trait中可以访问父类中的属性 return $this->name.'和'.$this->friend1.'在学习'.$name; } } } class Student extends Person { use Hobby, Recreation { Hobby::sport insteadof Recreation; Recreation::sport as mySport; } public static function hobby($name) { return $name; } public function study($course='斗地主') { return $this->name.'在学习'.$course; } } //实例化Student类 $student = new Student(); //1.访问父类Person中的方法 echo $student->study(); echo Student::hobby('抽烟喝酒'); echo '<hr>'; echo $student->sport(); echo '<hr>'; echo $student->mySport(); 运行实例 » 点击 "运行实例" 按钮查看在线实例