php组合

时间:2021-12-29 20:26:15

为了提高代码的复用性,降低代码的耦合(组合实现的两种方式)

模式一:

 <?php
//组合模式一
class Person{
public function eat(){
echo "eat.<br/>";
}
} class Phone{
public function call(){
echo "phone call.<br/>";
}
} //学生也需要call()这个方法,为了提高代码的复用性(组合)
class Student extends Person{
private $people;
public function learning(){
echo "learn.<br/>";
}
public function func($class, $method){//兼容多个类的多个方法
$this->people = new $class;
$this->people->$method();
}
} $student = new Student();
$student->eat();
$student->func('Phone', 'call');
$student->learning();

模式二:

 <?php
//组合模式二
class Person{
public function eat(){
echo "eat.<br/>";
}
} trait Drive{
public function call(){
echo "phone call.<br/>";
}
} class Student extends Person{
use Drive;
public function learning(){
echo "learn.<br/>";
}
} $student = new Student();
$student->eat(); //当方法或属性同名时,当前类中的方法会覆盖 trait的 方法,而 trait 的方法又覆盖了基类中的方法
$student->call();
$student->learning();