php类的单继承性,无法同时从两个基类中继承属性和方法,为了解决这个问题,使用Trait特性解决.
用法:通过在类中使用use 关键字,声明要组合的Trait名称,具体的Trait的声明使用Trait关键词. 注意:Trait不能实例化
demo示例:
1 <?php 2 trait Dog{ 3 ????public function dog(){ 4 ????echo ‘This trair dog‘; 5 ????} 6 } 7 ?8 trait Fish{ 9 ????public function fish(){10 ????echo ‘This trair fish‘;11 ????}12 }13 14 15 class Animal{16 ????public function name(){17 ????????echo ‘This is animal‘;18 ????}19 }20 21 class Cat extends Animal{22 ????use Dog,Fish;23 ????public function eat(){24 ????????echo ‘This is animal cat eat‘;25 ????}26 }27 28 $data = new Cat();29 $data->name();//This is animal30 echo ‘<pre>‘;31 $data->eat();//This is animal cat eat32 echo ‘<pre>‘;33 $data->dog();//This trair dog34 echo ‘<pre>‘;35 $data->fish();//This trair fish
结果打印:
PHP Trait特性
原文地址:https://www.cnblogs.com/cxx8181602/p/9815669.html