实例
<?php class animal { private $name = "动物"; public function __construct($name) { $this->name = $name; } public function speak() { echo $this->name . '正在说话...'; } } trait first_trait { private $name = '小狗'; public function speak() { echo $this->name . '正在汪汪叫...'; } } class Dog extends animal { public function __construct($name) { parent::__construct($name); } use first_trait; } $dog = new Dog('小狗'); $dog->speak();
运行实例 »
点击 "运行实例" 按钮查看在线实例
总结:
1. trait类似于一个方法集,不能被实例化
2. 同名方法的优先级:子类>Trait类>父类