PHP面向物件之繼承
阿新 • • 發佈:2020-12-10
繼承
-
介紹
- 繼承使得程式碼具有層次結構
- 子類繼承了父類的屬性和方法,實現了程式碼的可重用性
- 使用extends關鍵字實現繼承
- 父類和子類是相對的
-
語法
class 子類 extends 父類 {
}
- 執行過程
- 第一步:在Student類中查詢show(),如果找到就呼叫,找不到就到父類中查詢
- 第二步:在Person類中查詢show()
<?php class Person { public function show() { echo "嘿,人類!<br>"; } } class Student extends Person{ } $stu= new Student(); $stu->show(); ?>
子類中呼叫父類成員
- 方法
- 通過例項化父類呼叫父類的成員
- 通過$this關鍵字呼叫父類的成員
<?php class Person { public function show() { echo "嘿,人類!<br>"; } } class Student extends Person{ public function test1(){ $person= new Person(); $person->show(); } public function test2(){ $this->show(); } } $stu1= new Student(); $stu1->test1(); echo '<br>'; $stu2= new Student(); $stu2->test2(); ?>
protected
- protected
- 受保護的,在整個繼承鏈上使用
<?php
class A {
//在整個繼承鏈上訪問
protected $num= 10;
}
class B extends A {
public function getNum() {
echo $this->num;
}
}
//整個繼承鏈上有A和B
$obj= new B();
$obj->getNum();
?>
<?php class A { public function getNum() { echo $this->num; } } class B extends A { //在整個繼承鏈上訪問 protected $num= 10; } //整個繼承鏈上有A和B $obj= new B(); $obj->getNum(); ?>
<?php
class A {
public function getNum() {
echo $this->num;
}
}
class B extends A {
//在整個繼承鏈上訪問
protected $num= 10;
}
//整個繼承鏈上只有A
$obj= new A();
$obj->getNum();
?>
繼承中的建構函式
-
規則
- 如果子類有建構函式就呼叫子類的,如果子類沒有就呼叫父類的建構函式
- 子類的建構函式呼叫後,預設不再呼叫父類的建構函式
-
語法
- 通過類名呼叫父類的建構函式
- parent關鍵字表示父類的名字,可以降低程式的耦合性
# 通過類名呼叫父類的建構函式
父類類名::__construct();
# 通過parent關鍵字呼叫父類的建構函式
parent::__construct();
<?php
class Person {
//父類的建構函式
public function __construct() {
echo '這是父類<br>';
}
}
class Student extends Person {
//子類的建構函式
public function __construct() {
//通過父類的名字呼叫父類的建構函式
Person::__construct();
//parent表示父類的名字
parent::__construct();
echo '這是子類<br>';
}
}
new Student();
?>
- 案例
<?php
class Person {
protected $name;
protected $sex;
//父類的建構函式
public function __construct($name, $sex) {
$this->name= $name;
$this->sex= $sex;
}
}
class Student extends Person {
private $score;
//子類的建構函式
public function __construct($name, $sex, $score) {
parent::__construct($name, $sex); //呼叫父類建構函式並傳遞引數
$this->score= $score;
}
//顯示資訊
public function getInfo() {
echo "姓名:{$this->name}<br>";
echo "性別:{$this->sex}<br>";
echo "成績:{$this->score}";
}
}
//測試
$stu=new Student('sunny','男',28);
$stu->getInfo();
?>
$this詳解
- 概念
$this
表示當前物件的引用,也就是$this
儲存的當前物件的地址
<?php
class A {
public function __construct(){
var_dump($this);
}
}
class B extends A {
}
new A();
echo '<br>';
new B();
?>
多重繼承
- 概念
- PHP不允許多重繼承,因為多重繼承容易產生二義性
- 如何實現C繼承A和B,使用繼承鏈