透過一個「線上書店折扣結算」完整案例,展示 PHP OOP 核心概念:介面契約、抽象基類封裝共通邏輯、具體子類實作差異、靜態結算服務類,並說明建構子繼承規則 (PHP 4 vs 5+)。
parent::__construct()。__construct(),同名方法不再是建構子。<?php
// User.php
interface User {
public function getName();
public function setName($name);
public function getDiscount();
}
abstract class AbstractUser implements User {
private $name = '';
protected $discount = 0;
protected $grade = '';
public function __construct($name) { $this->setName($name); }
public function getName() { return $this->name; }
public function setName($name) { $this->name = $name; }
public function getDiscount() { return $this->discount; }
public function getGrade() { return $this->grade; }
}
class NormalUser extends AbstractUser { protected $discount = 1.0; protected $grade = 'NormalUser'; }
class VipUser extends AbstractUser { protected $discount = 0.8; protected $grade = 'VipUser'; }
class InnerUser extends AbstractUser { protected $discount = 0.7; protected $grade = 'InnerUser'; }
// Product.php
interface Product { public function getProductName(); public function getProductPrice(); }
interface Book extends Product { public function getAuthor(); }
class BookOnline implements Book {
private $productName, $productPrice, $author;
public function __construct($bookName) { $this->productName = $bookName; }
public function getProductName() { return $this->productName; }
public function getProductPrice() { return 100; } // 假設從 DB 讀取
public function getAuthor() { return $this->author; }
}
// ProductSettle.php
class ProductSettle {
public static function finalPrice(User $user, Product $product, $number = 1) {
return $user->getDiscount() * $product->getProductPrice() * $number;
}
}
// 使用
$book = new BookOnline('設計模式');
foreach ([new NormalUser('Tom'), new VipUser('Tom'), new InnerUser('Tom')] as $user) {
$price = ProductSettle::finalPrice($user, $book, 10);
echo "用戶:{$user->getName()} 等級:{$user->getGrade()} 折扣:{$user->getDiscount()} 價格:$price\n";
}
?>
User、Product、Book 定義契約,實作可自由替換。User 實作皆可傳入 finalPrice()。declare(strict_types=1) 嚴格模式。private string $name = '';。public readonly string $grade;。enum UserGrade: string { case Normal = 'NormalUser'; }。