Trait的作用
Trait是一种代码复用技术,为PHP的单继承限制提供了一套灵活的代码复用机制。
php从以前到现在一直都是单继承的语言,无法同时从两个基类中继承属性和方法,为了解决这个问题,php从5.4开始的版本出了Trait这个特性
Trait的使用方法
用法:通过在类中使用use 关键字,声明要组合的Trait名称,具体的Trait的声明使用Trait关键词,Trait不能实例化
trait demo1
{
public function hello1()
{
return __METHOD__;
}
}
trait demo2
{
public function hello2()
{
return __METHOD__;
}
}
class demo
{
use demo1,demo2;
public function hello()
{
return __METHOD__;
}
}
$d = new demo();
echo $d->hello();
echo $d->hello1();
echo $d->hello2();
Trait 的优先级问题
如果使用的Trait中的一个方法名称和父类的方法名重名怎么办?或者和调用类本身的方法名重名,或者引入了两个Trait,这两个Trait有相同的方法名称等等这些问题
1、 使用的Trait中的一个方法名称和父类的方法名重名
<?php
trait demo1
{
public function hello()//trait方法
{
return __METHOD__;
}
}
class Fdemo{
public function hello()//父类方法
{
return __METHOD__;
}
}
class demo extends Fdemo
{
use demo1;
}
$d = new demo();
echo $d->hello();//调用重名的方法
运行结果:
结论:trait类优先级高于父类
2、和调用类本身的方法名重名
trait demo1
{
public function hello()//trait方法
{
return __METHOD__;
}
}
class demo
{
use demo1;
public function hello()
{
return __METHOD__;
}
}
$d = new demo();
echo $d->hello();//调用重名的方法
运行结果:
结论:类本身的优先级高于所使用的Trait类
3、引入了两个Trait,这两个Trait有重名的方法
<?php
trait demo1
{
public function hello()
{
return __METHOD__;
}
}
trait demo2
{
public function hello()
{
return __METHOD__;
}
}
class demo
{
use demo1,demo2{
demo1::hello insteadof demo2;
demo2::hello as hello2;
}
public function hello()
{
return __METHOD__;
}
}
$d = new demo();
echo $d->hello();
echo $d->hello2();
两个Trait类有重名的方法,调用这个方法的时候是会报错的,可以用 as 起个别名或者insteadof 替换的方法解决