PHP类(四)-类的继承
类的继承就是从已经定义的类中继承数据,也可以重新定义或者加入一些数据。
被继承的类称为父类,基类,超类
继承的类称为子类,派生类
在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(); ?>
运行结果
子类重载父类
在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 __construct($name="Alex",$age=12,$sex="Male",$grade="Eight"){ parent::__construct($name,$age,$sex); //调用父类中原本被覆盖的构造方法,为从父类继承过来的属性赋初值 $this->grade = $grade; } function Say(){ parent::Say(); //调用父类中被覆盖的Say()方法 echo $this->name." is study in grade ".$this->grade.".And my age is ".$this->age; echo "<br>"; } } $p1 = new Student("John",16,"Male"); $p1->grade = 8; $p1->Say(); ?>
运行结果
类的继承的访问控制
访问控制有三种,public,private,protected
public为公有权限
private为私有权限,父类中设置为private权限,父类的外部和子类都不能访问
protected为保护权限,父类中设置为protected权限,父类的外部和子类的外部都不能访问,但是子类能访问的
<?php class Person{ protected $name = "Tom"; protected function Say(){ echo "My name is ".$this->name; } } class Man extends Person{ function Speak(){ echo $this->name." can speak Chinese"; } } $p1 = new Man(); $p1->Speak(); $p1->Say(); //在子类外部调用父类中受保护的方法 ?>
运行结果