PHP 面向对象OOP开发之子类对父类方法的重构
通常情况下我们会使用 class childClass extends parentClass{}来声明子类childClass继承了父类parentClass的属性和方法从而实现类的继承和重用。
子类对父类中不同访问类型的成员属性的访问权限如下:
访问类型 | private | protected | public |
---|---|---|---|
当前类中 | True | True | True |
子类中 | False | True | True |
类的外部 | False | False | True |
当父类中继承下来的方法并不能满足子类的需求,则需要对方法进行重写,声明一个与父类中同名的方法即可完成重写。
当父类中的方法可以被重新使用,则可通过使用parent::func()来调用父类中的方法,实现方法的复用。
<?php
// 父类方法的重构
// parent::func() 重载
class person{ //parent
public $name;
public $age;
public $sex;
public function __construct($name,$age,$sex){
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
public function property(){
echo "<h3>The Property for ".$this->name.":</h3>";
echo "<li> Name :".$this->name."</li>";
echo "<li> Age :".$this->age."</li>";
echo "<li> Sex :".$this->sex."</li>";
}
}
class boy extends person{
public $school;
public function __construct($name,$age,$sex,$school){
parent::__construct($name,$age,$sex);
# 如果写成parent::__construct() ,则成员属性无法继承
$this->school = $school;
}
public function property(){
parent::property();
echo "<li> School :".$this->school."</li>";
}
}
// $parent = new person('Green',51,'Male');
$boy = new boy('Jim',11,'Male','MingAn-School');
$boy->property();
以上代码会输出
The Property for Jerry:
- Name :Jim
- Age :11
- Sex :Male
- School :MingAn-School