在子类中重载父类的方法(重写方法)
class person{
protected $name;
protected $sex;
protected $age;
function __construct($name,$sex,$age){
$this->name=$name;
$this->sex=$sex;
$this->age=$age;
}
function say(){
echo "我的名字:".$this->name.";性别:".$this->sex.";年龄:".$this->age."。
";
}
}
class student extends person{
private $school;
//覆盖父类中的构造方法,在参数列表中多参加一个学校属性,用来创建对象并初始化成员属性
function __construct($name="",$sex="",$age="",$school=""){
$this->name=$name;
$this->sex=$sex;
$this->age=$age;
$this->school=$school;
}
function study(){
echo $this->name."正在".$this->school."学习。
";
}
//定义一个和父类中同名的方法,将父类中的说话方法覆盖并重写,多说出所在的学校名称
function say(){
echo "我的名字:".$this->name.";性别:".$this->sex.";年龄:".$this->age.";在".$this->school."上学。
";
}
}
$student1=new student("张三","男","20","一中");
$student1->study();
$student1->say();
?>
代码运行结果是: