1.一个trait可以供多个类来使用
<?php
trait Bt{
public function atest(){
echo 'hello ';
}
public function btest(){
echo 'world';
}
public function ab(){
$this->atest();
$this->btest();
}
}
//可以被多个类进行复用
//Test类 使用Bt
class Test{
use Bt;
}
$test=new Test();
$test->ab(); //hello world
//Tmp类 使用Bt
class Tmp{
use Bt;
}
$tmp=new Tmp();
$tmp->ab(); hello world
2.一个类可以使用多个trait,解决了类的单继承的问题
<?php
trait A{
public function a(){
echo 'hello ';
}
}
trait B{
public function b(){
echo 'world';
}
}
class Test{
use A,B;
public function c(){
echo '...';
}
}
$test=new Test();
$test->a();
$test->b();
$test->c();
//hello world...
?>
3.trait中可以定义属性
<?php
trait A{
public $abc="abc";//trait里面可以定义属性
}
class Test{
use A;
public function c(){
echo $this->abc; //输入trait A 中定义的属性
}
}
$test=new Test();
$test->c(); //abc
4.trait 可以嵌套使用
<?php
trait A{
public $abc="abc";//trait里面可以定义属性
public function a(){
echo 'hello ';
}
}
trait B{
public function b(){
echo 'world';
}
}
//trait C 嵌套 A B
trait C{
use A,B;
}
class Test{
use C;
public function c(){
echo $this->abc; //输入trait A 中定义的属性
}
}
$test=new Test();
$test->a();
$test->b();
$test->c();
//hello world abc
?>
5.trait的优先级
<?php
/**
* 讨论trait的优先级
*1.当前类中的方法与trait类,父类中的方法重名,该怎么办?
* 当前类优先级最高,trait类次之,父类最低
*/
//声明父类
class Test
{
public function hello()
{
return __METHOD__;
}
}
//trait类
trait Demo1{
public function hello(){
return __METHOD__;
}
}
//实例类
class Demo extends Test
{
use Demo1;
public function hello()
{
return __METHOD__;
}
}
$obj=new Demo();
echo $obj->hello();
#优先级 Demo>Demo1>Test