首页> 基础笔记 >PHP基础学习 >面向对象 面向对象
PHP面向对象子类中重载父类的方法
作者:小萝卜 2019-09-01 【 PHP 面向对象 】 浏览 1170
简介在子类里面允许重写(覆盖)父类的方法,在子类中,使用parent访问父类中的被覆盖的属性和方法
子类中重载父类的方法
在子类里面允许重写(覆盖)父类的方法
在子类中,使用parent访问父类中的被覆盖的属性和方法
parent::__construce();
parent::fun();
<?php
class Person {
protected $name;
protected $sex;
public function __construct($name=“”, $sex=“男”) { ...属性赋值 }
public function say(){ ...输出属性信息 }
}
class Student extends Person { //声明学生类,使用extends继承Person类
private $school;
//构造方法重写(覆盖)
public function __construct($name="", $sex="男", $school="") {
parent::__construct($name,$sex); //调用父类构造方法,初始化父类
$this->school = $school; //新添加一条为子类中新声明的成员属性赋初值
}
public function say( ) { //方法重写(覆盖)
parent::say(); //调用父类中被本方法覆盖掉的方法
echo "在".$this->school."学校上学<br>"; //在原有的功能基础上多加一点功能
}
}
$student = new Student("张三","男",20, "edu"); //创建学生对象,并多传一个学校名称参数
$student->say(); //调用学生类中覆盖父类的说话方法
很赞哦! (0)