实例
<?php /** * Created by PhpStorm. * User: 金超 * Date: 2018/5/8 * Time: 9:52 */ //先创建一个父类 if(!class_exists('engineer')) { class engineer { protected $name; public function __construct($name='kim') { $this->name=$name; } public function duty($lang='php') { return $this->name.'的职责是写'.$lang; } } } //第一个trait if(!trait_exists('Mission')){ trait Mission { public $boss='Jack'; public function task($job='写网页') { return $this->boss.'给'.$this->name.'下达了'.$job.'的任务'; } } } //再写一个trait if(!trait_exists('Recess')) { trait Recess { public $leader='Rose'; public function task($day='三'){ return $this->leader.'觉得'.$this->name.'工作太辛苦了,于是给'.$this->name.'放了'.$day.'天假'; } } } //子类 if(!class_exists('programmer')) { class programmer extends engineer { //子类支持导入多个trait类,方法重名的话用下列方法解决 use Mission,Recess{ //重名的task 用Mission::task代替掉Recess::task Mission::task insteadof Recess; //在用holiday代替Recess::task Recess::task as holiday; } } } //实例化子类 $programmer=new programmer(); //调用父类中的方法 echo $programmer->duty(); echo'<hr style="color:aquamarine">'; //访问trait类中的方法 echo $programmer->task(); echo'<hr style="color:blueviolet">'; //调用trait中重名的方法 echo $programmer->holiday(); echo'<hr style="color:cornflowerblue">';
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例