如下:C类想用A Trait和B Trait的方法,但是属性名冲突,报错。
Fatal error: A and B define the same property ($prop) in the composition of C. However, the definition differs and is considered incompatible. Class was composed。
trait A {
public $prop = 'trait_a';
public function speakEnglish() {
echo 'English';
}
}
trait B {
public $prop = 'trait_b';
public function speakChinese() {
echo '中文';
}
}
class C {
use A,B;
}
$c = new C();
echo $c->prop;
复制代码
错误的解决方案
PHP语言本身可以用insteadof和as关键字解决多个trait同名成员方法冲突的问题,但是这无法修饰成员属性。
报错:Fatal error: A precedence rule was defined for A::prop but this method does not exist.