实例
<?php //申明一个父类:Person class Person { public $name; //初始化$name public function __construct($name = '小明') { $this->name = $name; } //申明一个run()方法 public function run() { return $this->name . '在跑'; } } //申明trait trait myTrait { public $friend = '小花'; public function eat() { return $this->name . '吃东西'; } public function run() { return $this->name."和".$this->friend.'在跑'; } public function study($course = 'java') { return $this->name . '在学习' . $course; } } class Student extends Person { //使用trait use myTrait; //重写study()方法 public function study($course='python') { return $this->name.'在学习'.$course; } } $study = new Student(); echo $study->run().'<br>'; echo $study->eat().'<br>'; echo $study->study().'<br>';
运行实例 »
点击 "运行实例" 按钮查看在线实例
最终效果: