模式一:
1 php 2 //组合模式一 3 class person{ 4 public function eat(){ 5 echo eat.
; 6 } 7 } 8 9 class phone{10 public function call(){11 echo phone call.
;12 }13 }14 15 //学生也需要call()这个方法,为了提高代码的复用性(组合)16 class student extends person{17 private $people;18 public function learning(){19 echo learn.
;20 }21 public function func($class, $method){//兼容多个类的多个方法22 $this->people = new $class;23 $this->people->$method();24 }25 }26 27 $student = new student();28 $student->eat();29 $student->func('phone', 'call');30 $student->learning();
模式二:
1 php 2 //组合模式二 3 class person{ 4 public function eat(){ 5 echo eat.
; 6 } 7 } 8 9 trait drive{10 public function call(){11 echo phone call.
;12 }13 }14 15 class student extends person{16 use drive;17 public function learning(){18 echo learn.
;19 }20 }21 22 $student = new student();23 $student->eat();24 25 //当方法或属性同名时,当前类中的方法会覆盖 trait的 方法,而 trait 的方法又覆盖了基类中的方法26 $student->call();27 $student->learning();
view code
