# PHP trait新特性 1. trait作用 > trait是一种为类似 PHP 的单继承语言而准备的代码复用机制。trait为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用方法集。trait和类组合的语义是定义了一种方式来减少复杂性,避免传统多继承和混入类(Mixin)相关的典型问题。 2. trait使用方法: 声明: ~~~ <?php //声明一个trait 就是用trait 开头,像声明一个类一样,只不过类是class,而trait 就是用trait声明而已 trait Drive { //像类一样也有属性 public $carName = "tarit"; //像类一样,也有方法 public function driving() { echo "driving {$this->carName}<br>"; } } ~~~ 使用: ~~~ <?php class Student { //注意这里与命名空间的区别 use Drive; } ~~~ 注意:当方法或属性同名时,当前类中的方法会覆盖 trait的 方法,而 trait 的方法又覆盖了基类中的方法 ## 多个tarit组合时,解决冲突问题 如: ~~~ <?php trait Trait1 { public function hello() { echo "Trait1::hello\n"; } public function hi() { echo "Trait1::hi\n"; } } trait Trait2 { public function hello() { echo "Trait2::hello\n"; } public function hi() { echo "Trait2::hi\n"; } } class Class1 { use Trait1, Trait2; } ~~~ 使用insteadof和as操作符来解决冲突,insteadof是使用某个方法替代另一个,而as是给方法取一个别名,具体用法请看代码: ~~~ <?php trait Trait1 { public function hello() { echo "Trait1::hello<br/>"; } public function hi() { echo "Trait1::hi<br/>"; } } trait Trait2 { public function hello() { echo "Trait2::hello<br/>"; } public function hi() { echo "Trait2::hi<br/>"; } } class Class1 { use Trait1, Trait2 { Trait2::hello insteadof Trait1; Trait1::hi insteadof Trait2; } } class Class2 { use Trait1, Trait2 { Trait2::hello insteadof Trait1; Trait1::hi insteadof Trait2; Trait2::hi as hei; Trait1::hello as hehe; } } $Obj1 = new Class1(); $Obj1->hello(); $Obj1->hi(); echo "<br/>"; $Obj2 = new Class2(); $Obj2->hello(); $Obj2->hi(); $Obj2->hei(); $Obj2->hehe(); ~~~ 输出: ~~~ Trait2::hello Trait1::hi Trait2::hello Trait1::hi Trait2::hi Trait1::hello ~~~ TP5tarit的用法: <embed src="http://www.tudou.com/v/80AGv_9KZ4U/&bid=05&rpid=1059277519&resourceId=1059277519_05_05_99/v.swf" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="opaque" width="865" height="523"></embed> 下载地址:http://pan.baidu.com/s/1i4ZWdj3 TP5粉丝群: 543608226 TP5底层答疑群: 451935051