我们在类当中我往往会用到一些对象,此时的继承就无法满足我们的需求,这个时候我们需要用到组合。继承如果是is..a的关系,那么组合就是has...a的关系,直接在本类里面声明即可,不过声明的是一个对象
代码:我定义一个Score类,作为Student类的一个组合类
class Score
{
public $english;
public $chinese;
public $math;
function __construct($english,$chinese,$math)
{
$this->chinese = $chinese;
$this->english = $english;
$this->math = $math;
}
}
class Student
{
public $name;
public $age;
public $Score;
function __construct($name,$age,Score $Score)
{
$this->name = $name;
$this->age = $age;
$this->Score = $Score; //对象
}
function show(){
echo "我叫{$this->name},今年{$this->age}岁了,
数学:{$this->Score->math},英语:{$this->Score->english},
语文:{$this->Score->chinese}。";
} }
在main主页面进行实例化
include_once "Score.class.php";
include_once "Student.class.php";
$score = new Score(100,99,98);
$student = new Student("房明",18,$score);
$student->show();