- 如果在一个子类继承的多个父类中拥有相同名字的实例变量,子类在引用该变量时将产生歧义,无法判断应该使用哪个父类的变量。
- 如果在一个子类继承的多个父类中拥有相同方法,子类中有没有覆盖该方法,那么调用该方法时将产生歧义,无法判断应该调用哪个父类的方法。
Trait和Class相似,但仅仅旨在用细粒度和一致的方式来组合功能。无法通过trait自身来实例化。它为传统继承增加了水平特性的组合。
Trait使用case
优先级
对于方法:
当前类的成员>trait的方法>从基类继承的成员
对于变量:
当前类和基类中不能存在与trait重名的变量,否则会抛出fatal error。
多个trait
通过逗号分隔,在use声明中列出多个trait,可以都插入到一个类中。
如果两个trait都插入了一个同名的方法,如果没有明确解决冲突将会产生一个致命错误。为了解决多个trait在同一个类中的命名冲突,需要使用insteadof操作符来明确指定使用冲突方法中的哪一个。或者使用as操作符,可以将其中一个冲突的方法以另一个名称来引入。
同样的,如果两个trait有同名的变量,如果该属性的定义兼容(同样的可见性及初始值)错误级别是E_STRICT,否则错误级别是E_ERROR.
且不能通过解决方法冲突的方式解决。
修改方法的访问控制
指定alias会创建一个新的方法,原方法访问控制权限不变。不仅可以缩小权限的方向修改(public->private),也可以向放大权限的修改(private->public).
从trait来组成trait
与Class中使用多个trait类似,trait也可以使用多个trait。冲突的解决方式也一致。
Trait的抽象成员
为了对使用的类施加强制要求,trait支持抽象方法的使用。
Trait的静态成员
trait可以定义静态变量,静态方法。