繼承讓子類(BookProduct、CdProduct)自動擁有父類(ShopProduct)的公共屬性與方法,並可擴展或覆寫特有行為,實現代碼復用與多態。
<?php
class ShopProduct {
public $title;
public $producerFirstName;
public $producerMainName;
public $price;
public $numPages = 0;
public $playLength = 0;
public function __construct($title, $firstName, $mainName, $price, $numPages = 0, $playLength = 0) {
$this->title = $title;
$this->producerFirstName = $firstName;
$this->producerMainName = $mainName;
$this->price = $price;
$this->numPages = $numPages;
$this->playLength = $playLength;
}
public function getProducer() {
return "{$this->producerFirstName} {$this->producerMainName}";
}
public function getSummaryLine() {
return "{$this->title} ({$this->producerMainName}, {$this->producerFirstName})";
}
}
class CdProduct extends ShopProduct {
public function getPlayLength() { return $this->playLength; }
public function getSummaryLine() {
$base = parent::getSummaryLine(); // 復用父類邏輯
return "$base:播放時長 - {$this->playLength}";
}
}
class BookProduct extends ShopProduct {
public function getNumberOfPages() { return $this->numPages; }
public function getSummaryLine() {
$base = parent::getSummaryLine();
return "$base:頁數 - {$this->numPages}";
}
}
$product1 = new BookProduct("PHP 面向對象", "郭", "碗瓢盆", 79, 300);
$product2 = new CdProduct("Laravel 實戰", "李", "四", 99, 0, "10小時");
echo $product1->getSummaryLine(); // PHP 面向對象 (碗瓢盆, 郭):頁數 - 300
echo $product2->getSummaryLine(); // Laravel 實戰 (四, 李):播放時長 - 10小時
// 子類物件可直接呼叫父類方法
echo $product2->getProducer(); // 李 四
title、producer、pricenumPages,CD 管 playLengthparent:::避免重複邏輯,確保父類核心邏輯變更自動傳遞parent::__construct(...) 確保父類狀態正確初始化