隨著專案規模增長,程式碼維護性與擴充性成為關鍵。本文系統介紹 PHP 物件導向程式設計(OOP)核心概念、進階技巧,並示範如何應用於大型專案架構。
透過類別隱藏內部實作細節,僅公開必要介面:
<?php
class User {
private $id;
private $email;
private $passwordHash;
public function __construct(string $email, string $password) {
$this->email = $email;
$this->passwordHash = password_hash($password, PASSWORD_BCRYPT);
}
public function verifyPassword(string $password): bool {
return password_verify($password, $this->passwordHash);
}
// 僅提供必要的 getter,不提供 password setter
public function getEmail(): string {
return $this->email;
}
}
?>
關鍵點:使用 `private`/`protected` 限制存取,避免外部直接操作內部狀態(如 `$user->password = '123'`)。PHP 7.1+ 支援型別宣告與回傳型別,強化契約。
子類別繼承父類別特性,並可擴充或覆寫:
<?php
abstract class BaseModel {
protected $pdo;
protected $table;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function findById(int $id): ?array {
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}
}
class UserModel extends BaseModel {
protected $table = 'users';
public function findByEmail(string $email): ?array {
$stmt = $this->pdo->prepare("SELECT * FROM {$this->table} WHERE email = ?");
$stmt->execute([$email]);
return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}
}
?>
注意:PHP 不支援多重繼承,但可用 trait 實現程式碼複用。
同一介面,不同實作:
<?php
interface PaymentGateway {
public function charge(float $amount, string $currency): bool;
}
class StripeGateway implements PaymentGateway {
public function charge(float $amount, string $currency): bool {
// Stripe API 呼叫
return true;
}
}
class PayPalGateway implements PaymentGateway {
public function charge(float $amount, string $currency): bool {
// PayPal API 呼叫
return true;
}
}
// 使用端不需知道具體實作
function processOrder(PaymentGateway $gateway, float $amount) {
$gateway->charge($amount, 'TWD');
}
?>
PHP 原生 `serialize()` / `unserialize()` 僅保存屬性,不保存方法。現代專案建議:
掌握 OOP 核心概念並配合現代工具鏈(Composer、PHPUnit、PHPStan、CI/CD),才能駕馭大型 PHP 專案的複雜度,打造可維護、可測試、可擴充的高品質軟體。