本系列第二篇深入講解 PHP 繼承機制、建構函式用法、多重繼承限制、方法覆寫、資料成員遮蔽,以及模擬抽象類別的技巧。
使用 extends 關鍵字,衍生類別擁有父類別所有資料成員與方法,並可新增自身成員:
<?php
class Another extends Something {
var $y;
function setY($v) { $this->y = $v; }
function getY() { return $this->y; }
}
?>
PHP 不支援多重繼承,無法同時繼承兩個以上類別。
與類別同名的方法,new 實例化時自動呼叫:
<?php
class Something {
var $x;
function Something($y) { $this->x = $y; }
function setX($v) { $this->x = $v; }
function getX() { return $this->x; }
}
$obj = new Something(6); // $x = 6
?>
支援預設參數(C++ 風格,左至右綁定):
function Something($x="3", $y="5") {
// new Something() -> x=3, y=5
// new Something(8) -> x=8, y=5
// new Something(8,9) -> x=8, y=9
}
衍生類別實例化時不會自動呼叫父類別建構函式,需在衍生類別建構函式中顯式呼叫:
function Another() {
$this->y = 5;
$this->Something(); // 顯式呼叫父類別建構函式
}
PHP 無標準抽象類別機制,可透過在基底類別建構函式與介面方法加入 die() 防止實例化與強制覆寫:
class Base {
function Base() { die("Base class cannot be instantiated"); }
function interfaceMethod() { die("Must override in derived class"); }
function getClassID() { return "BASE_ID"; } // 身分驗證
}
另可在基底類別加入身分識別方法,接收物件參數時驗證來源。注意:惡意程式設計師仍可覆寫驗證方法,防禦重點在懶惰而非惡意者。
PHP 無解構函式(destructor)。