自 PHP 5.4.0 起,PHP 实现了一种代码复用的方法,称为 trait。
Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式,避免传统多继承和 Mixin 类相关典型问题。
Trait 和 Class 相似,但仅仅旨在用细粒度和一致的方式来组合功能。 无法通过 trait 自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用的几个 Class 之间不需要继承。
从基类继承的成员会被 trait 插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了 trait 的方法,而 trait 则覆盖了被继承的方法。
以下为代码:
trait traitTestOne{
public function test(){
echo "This is trait one ";
}
public function testOne(){
echo "one ";
}
}
trait traitTestTwo{
// public function test(){
// echo "This is trait two";
// }
public function testTwo(){
echo "two ";
}
}
class basicTest{
public function test(){
echo "hello world\n";
}
}
class myCode extends basicTest{
use traitTestOne,traitTestTwo;
}
$test = new mycode();
$test->test();
$test->testOne();
$test->testTwo();
下面是输出:
This is trait one
one
two
注意。如果把注释一行的注释取消,将会报错
Fatal error: Trait method test has not been applied, because there are collisions with other trait methods on myCode in ……test.php on line 28
是致命错误。