概念
用于模拟实现多继承。由于php只支持单继承,要实现继承多个类就成了难题了,而trait正是为了解决这个难题而诞生的。
特点
- 定义trait要以trait关键字开头,其他与类无异。
- 一般trait不加成员属性,只加成员方法
- trait的方法要想被引入的类使用,只能用public修饰
- trait不能实例化
- trait可以引入trait
class person
{
use coat;
use pants;
public function getEquipment()
{
$this->getCoat();
$this->getPants();
}
}
trait coat
{
public function getCoat()
{
echo "装备上衣</br>";
}
}
trait pants
{
public function getPants()
{
echo "装备裤子</br>";
}
}
$hero = new person();
$hero->getEquipment();
其他
- 解决不同的trait方法名冲突
- 覆盖
使用 insteadof
- 别名
使用 as
class person
{
use coat{
coat::getName as getCodeName;
}
use pants{
pants::getName insteadof coat;
}
public function getEquipment()
{
$this->getCodeName("上衣");
$this->getName("裤子");
}
}
trait coat
{
public function getName($name)
{
echo "</br>装备名称:" . $name;
}
public function getCoat()
{
echo "装备上衣</br>";
}
}
trait pants
{
public function getName($name)
{
echo "</br>装备名称:" . $name;
}
public function getPants()
{
echo "装备裤子</br>";
}
}
$hero = new person();
$hero->getEquipment();