PHP是单继承的语言,在PHP 5.4 Traits出现之前,PHP的类无法同时从两个基类继承属性或方法。php的Traits和Go语言的组合功能有点类似,
通过在类中使用use关键字声明要组合的Trait名称,而具体某个Trait的声明使用trait关键词,Trait不能直接实例化。具体用法请看下面的代码:
<?php trait Drive { public $carName = 'BMW'; public function driving() { echo "driving {$this->carName}\n"; } } class Person { public function age() { echo "i am 18 years old\n"; } } class Student extends Person { use Drive; public function study() { echo "Learn to drive \n"; } } $student = new Student(); $student->study(); $student->age(); $student->driving();
Learn to drive i am 18 years old driving BMW
上面的例子中,Student类通过继承Person,有了age方法,通过组合Drive,有了driving方法和属性carName。
如果Trait、基类和本类中都存在某个同名的属性或者方法,最终会保留哪一个呢?通过下面的代码测试一下:待续