实例
<?php if (!class_exists('Chief')) { class Chief { protected $name; public function __construct($name = '厨师长') { $this->name = $name; } public function cook($food = '番茄炒蛋') { return $this->name.'在烧'.$food; } } } if (!trait_exists('Dish')) { trait Dish { public $customer = '顾客'; public function eat($vegetable = '蔬菜') { return $this->customer.'在品尝'.$this->name.'烧的'.$vegetable; } abstract public static function special($name); public function cook($food = '蛋黄南瓜') { return $this->customer.'在试吃'.$food; } } class Apprentice extends Chief { use Dish; protected $name; public function __construct($name = '学徒') { $this->name = $name; } public function special($name = '糖醋排骨') { return $this->name.'特别擅长烧'.$name; } public function cook($food = '啤酒茄盒') { return $this->name.'在试吃'.$food; } } } $apprentice = new Apprentice(); echo $apprentice->special().'<br>'; echo $apprentice->cook().'<br>'; echo $apprentice->eat().'<br>';
运行实例 »
点击 "运行实例" 按钮查看在线实例
总结:
trait是为单继承语言量身定制的代码复用机制
trait简单理解为一个方法集合
trait可以看作是一个特殊的类,但不能被实例化,仅允许被类调用
使用关键字use
优先级为子类>trait>父类