萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 物件導向程式設計 (OOP) 入門:介面、抽象類別、建構子繼承與結算範例

透過一個「線上書店折扣結算」完整案例,展示 PHP OOP 核心概念:介面契約、抽象基類封裝共通邏輯、具體子類實作差異、靜態結算服務類,並說明建構子繼承規則 (PHP 4 vs 5+)。

建構子繼承規則

  • **子類未定義建構子** → 自動繼承父類建構子。
  • **子類定義建構子** → **不會**自動呼叫父類建構子,需手動 parent::__construct()。
  • PHP 4 以同名方法為建構子;PHP 5+ 統一用 __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()。
  • 單一職責:結算邏輯獨立於實體類別。
  • 開閉原則:新增用戶類型/產品類型無需修改結算類。

現代 PHP 建議

  • 使用 declare(strict_types=1) 嚴格模式。
  • 屬性型別宣告 (PHP 7.4+):private string $name = '';。
  • 唯讀屬性 (PHP 8.1+):public readonly string $grade;。
  • Enum (PHP 8.1+) 替代字串常數:enum UserGrade: string { case Normal = 'NormalUser'; }。
copyright © 萬盛學電腦網 all rights reserved