parent::?當子類定義自己的構造函數或覆寫父類方法時,若不顯式調用父類實現,會導致父類初始化邏輯缺失或核心功能被完全替換。parent:: 提供了訪問父類作用域的管道。
class ShopProduct {
public $title, $producerFirstName, $producerMainName, $price;
public function __construct($title, $firstName, $mainName, $price) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
}
}
class CdProduct extends ShopProduct {
public $playLength;
public function __construct($title, $firstName, $mainName, $price, $playLength) {
parent::__construct($title, $firstName, $mainName, $price); // 必須先初始化父類
$this->playLength = $playLength;
}
}
class BookProduct extends ShopProduct {
public $numPages;
public function __construct($title, $firstName, $mainName, $price, $numPages) {
parent::__construct($title, $firstName, $mainName, $price);
$this->numPages = $numPages;
}
}
// 父類
public function getSummaryLine() {
return "{$this->title} ({$this->producerMainName}, {$this->producerFirstName})";
}
// 子類 CdProduct
public function getSummaryLine() {
$base = parent::getSummaryLine(); // 獲取父類格式化字串
return "$base:播放時長 - {$this->playLength}";
}
// 子類 BookProduct
public function getSummaryLine() {
$base = parent::getSummaryLine();
return "$base:頁數 - {$this->numPages}";
}
parent::method() 編譯期解析為父類具體函數地址,運行期無多態查找開銷parent::__construct() 導致父類屬性未初始化$this 或調用非靜態方法Declaration must be compatible 錯誤)