核心概念
| 術語 | 說明 |
| 類別 | 模板/藍圖,定義屬性 (資料) 與方法 (行為) |
| 物件 | 類別的實例,佔有獨立記憶體空間存放屬性值 |
| 封裝 | 將資料與操作資料的方法綁定,隱藏內部細節 (visibility) |
| 繼承 | 子類別重用/擴充父類別功能,建立 is-a 關係 |
| 多型 | 相同介面不同實作,執行期依物件型別動態分派 |
| 抽象 | 定義介面/抽象類別規範契約,延後具體實作 |
PHP 類別定義語法 (PHP 8.2+)
<?php
declare(strict_types=1);
namespace App\Model;
class User {
// 屬性 (Property) - 可視性:public/protected/private
public readonly string $uuid; // PHP 8.1 readonly
public string $name;
protected string $email;
private string $passwordHash;
private static int $instanceCount = 0; // 靜態屬性
// 建構子 (Constructor) - PHP 8.0 提升屬性
public function __construct(
public readonly string $uuid, // 同時宣告屬性並接收參數
string $name,
string $email,
string $password
) {
$this->name = $name;
$this->email = $email;
$this->passwordHash = password_hash($password, PASSWORD_BCRYPT);
self::$instanceCount++;
}
// 方法
public function verifyPassword(string $password): bool {
return password_verify($password, $this->passwordHash);
}
// 靜態方法
public static function getInstanceCount(): int {
return self::$instanceCount;
}
// 魔術方法
public function __toString(): string {
return "User({$this->uuid}) {$this->name}";
}
// 解構子
public function __destruct() {
self::$instanceCount--;
}
}
// 繼承
class AdminUser extends User {
public array $permissions = [];
public function __construct(string $uuid, string $name, string $email, string $password, array $permissions = []) {
parent::__construct($uuid, $name, $email, $password);
$this->permissions = $permissions;
}
public function hasPermission(string $perm): bool {
return in_array($perm, $this->permissions, true);
}
}
// 介面
interface Loggable {
public function log(string $message): void;
}
// Trait 程式碼複用
trait Timestampable {
public DateTimeImmutable $createdAt;
public ?DateTimeImmutable $updatedAt = null;
public function touch(): void {
$this->updatedAt = new DateTimeImmutable();
}
}
?>
物件實例化與存取
<?php
$user = new User(
uuid: 'usr_' . bin2hex(random_bytes(8)),
name: 'Alice',
email: 'alice@example.com',
password: 'secret123'
);
echo $user->name; // 存取 public 屬性
echo $user->verifyPassword('secret123') ? 'OK' : 'Fail'; // 呼叫方法
echo User::getInstanceCount(); // 靜態方法呼叫
$admin = new AdminUser('adm_...', 'Bob', 'bob@admin', 'pwd', ['user.manage', 'log.view']);
$admin->touch(); // 來自 Trait
?>
可視性與封裝最佳實踐
- private:僅本類別存取,繼承類別不可見 (最嚴格封裝)。
- protected:本類別 + 子類別可存取 (開放擴充)。
- public:任意處存取 (定義公共 API)。
- **原則**:屬性預設
private,透過 getter/setter 或 readonly 控制存取;方法盡量 public 或 protected。
靜態成員 vs 實例成員
| 特性 | 靜態 | 實例 |
| 所屬 | 類別 | 物件 |
| 記憶體 | 單一份 (共享) | 每個物件一份 |
| 存取 | Class::$prop, Class::method() | $obj->prop, $obj->method() |
$this 可用 | 否 | 是 |
| 繼承行為 | 共享同一儲存 (Late Static Binding 解決) | 各自獨立 |
現代 PHP OOP 進階特性
- 建構子屬性提升 (PHP 8.0) 減少樣板代碼。
- readonly 屬性 (PHP 8.1) 確保不可變性。
- enum (PHP 8.1) 替代常數類別,支援方法與介面。
- final class/method 禁止繼承/覆寫。
- 介面 + Trait 組合優於深層繼承。
- 依賴注入:建構子注入介面型別,配合容器 管理生命週期。
自動載入
// composer.json
{
"autoload": {
"psr-4": { "App\\": "src/" }
}
}
執行 composer dump-autoload 後,直接 use App\Model\User; 即可使用,無需 require。
常見錯誤與避坑
- 忘記
parent::__construct() 導致父類別初始化遺漏。
- 靜態屬性在繼承中共享同一記憶體,子類別修改影響父類別 (使用
static:: 延遲靜態綁定)。
- 在建構子中呼叫虛擬方法 (子類別可能尚未初始化完成)。
- 過度使用繼承導致脆弱基類問題,優先考慮組合。
- 循環引用導致記憶體洩漏 (PHP 5.3+ 循環垃圾收集器會處理,但需注意
__destruct 順序)。