一,Trart用途:可以使子类无法从多个类中继承属性和方法
实例
class animal{ public function a(){ echo 'this is animal.'; } } trait cat{ public function b(){ echo 'this is cat.'; } } trait pig{ public function c(){ echo 'this is pig;'; } } class dog extends animal{ use cat; use pig; public function get(){ echo 'this is big dog.'; } } $dog=new dog(); $dog->a();//返回this is animal. echo '<br>'; $dog->b();//返回this is cat. echo '<br>'; $dog->c();//返回this is pig;
运行实例 »
点击 "运行实例" 按钮查看在线实例
二,当子类中有和trait中重名的属性和方法时,trait中的属性和方法会被覆盖
实例
实例 trait pig{ public function c(){ echo 'this is pig;'; } } class dog extends animal{ use cat; use pig; public function c(){ echo 'this is big dog.'; } } $dog=new dog(); $dog->a();//返回this is animal. echo '<br>'; $dog->b();//返回this is cat. echo '<br>'; $dog->c();//返回this is big pig;
运行实例 »
点击 "运行实例" 按钮查看在线实例
实例
trait pig{ public function c(){ echo 'this is pig;'; } } class dog extends animal{ use cat; use pig; public function c(){ echo 'this is big dog.'; } } $dog=new dog(); $dog->a();//返回this is animal. echo '<br>'; $dog->b();//返回this is cat. echo '<br>'; $dog->c();//返回this is big pig;
运行实例 »
点击 "运行实例" 按钮查看在线实例
三,当trait和父类中有同名的属性和方法时,父类中的属性和方法将会被 trait中的属性和方法覆盖
实例
class animal{ public function a(){ echo 'this is animal.'; } } trait cat{ public function a(){ echo 'this is cat.'; } } class dog extends animal{ use cat; public function c(){ echo 'this is big dog.'; } } $dog=new dog(); $dog->a();//返回this is cat.
运行实例 »
点击 "运行实例" 按钮查看在线实例
总结:trait可以实现一个子类引用其父类之外的属性和方法,当有同名的属性和方法时,优先级为:子类>trait>父类