类的继承就是从已经定义的类中继承数据,也可以重新定义或者加入一些数据。
被继承的类称为父类,基类,超类
继承的类称为子类,派生类
在PHP中只能使用单继承,也就是一个类只能从一个类中继承数据,但是一个类可以有多个子类
<?php class Person{ var $name; var $age; var $sex; function __construct($name="Alex",$age=12,$sex="Male"){ $this->name = $name; $this->age = $age; $this->sex = $sex; } function Say(){ echo "My name is ".$this->name.",and my age is ".$this->age.",sex is ".$this->sex; echo "<br>"; } } class Student extends Person{ var $grade; function Study(){ echo $this->name." is study in grade ".$this->grade.".And My age is ".$this->age; echo "<br>"; } } class Teacher extends Person{ var $subject; function Teach(){ echo $this->name." teaches ".$this->subject; echo "<br>"; } } $p1 = new Student("John",16,"Male"); $p1->Say(); $p1->grade = 8; $p1->Study(); $p2 = new Teacher("Tom",23,"Male"); $p2->Say(); $p2->subject = "PHP"; $p2->Teach(); ?>
运行结果