PHP 5 起完整支援物件導向程式設計 (OOP),PHP 7/8 更大幅強化型別系統、效能與語法糖。本文從基本類別定義、屬性方法、可視性、建構子解構子、靜態成員、繼承介面、Trait、魔術方法到現代最佳實務,系統建立 PHP OOP 完整知識體系。
基本類別定義
<?php
class Calculator
{
// 屬性 (Properties) - PHP 7.4+ 型別宣告
public int $precision = 2;
protected string $lastOperator = '';
private float $memory = 0.0;
// 建構子
public function __construct(int $precision = 2)
{
$this->precision = $precision;
}
// 公開方法
public function add(float $a, float $b): float
{
$this->lastOperator = '+';
return round($a + $b, $this->precision);
}
public function subtract(float $a, float $b): float
{
$this->lastOperator = '-';
return round($a - $b, $this->precision);
}
public function multiply(float $a, float $b): float
{
$this->lastOperator = '*';
return round($a * $b, $this->precision);
}
// 受保護方法 (子類別可存取)
protected function setMemory(float $value): void
{
$this->memory = $value;
}
// 公開存取器
public function getMemory(): float
{
return $this->memory;
}
public function memoryAdd(float $value): void
{
$this->memory += $value;
}
// 解構子
public function __destruct()
{
// 清理資源、關閉連線、寫入日誌等
}
}
建立物件與呼叫方法
<?php
require 'Calculator.php';
// 實例化
$calc = new Calculator(4); // 精度 4 位小數
// 呼叫方法
echo $calc->add(10.1234, 5.5678); // 15.6912
echo $calc->subtract(20.5, 8.25); // 12.25
echo $calc->multiply(3.14159, 2); // 6.2832
// 存取公開屬性
$calc->precision = 3;
echo $calc->add(1.111, 2.222); // 3.333
// 存取記憶體功能
$calc->memoryAdd(100);
echo $calc->getMemory(); // 100
可視性控制
| 關鍵字 | 類別內部 | 子類別 | 外部程式碼 |
| public | ✅ | ✅ | ✅ |
| protected | ✅ | ✅ | ❌ |
| private | ✅ | ❌ | ❌ |
靜態成員與延遲靜態綁定
<?php
class Model
{
protected static string $table = 'base_table';
public static function getTable(): string
{
return static::$table; // 延遲靜態綁定 (Late Static Binding)
}
public static function create(array $data): static
{
// 回傳當前實際類別的實例 (PHP 8.0+ static 回傳型別)
return new static($data);
}
}
class User extends Model
{
protected static string $table = 'users';
}
echo User::getTable(); // 'users' (非 'base_table')
繼承、介面與 Trait
<?php
// 介面定義契約
interface Loggable
{
public function log(string $message): void;
}
// Trait 程式碼複用
trait Timestampable
{
public DateTime $createdAt;
public DateTime $updatedAt;
public function touch(): void
{
$this->updatedAt = new DateTime();
}
}
// 實作類別
class Article implements Loggable
{
use Timestampable;
public function __construct(
public string $title,
public string $content
) {
$this->createdAt = new DateTime();
$this->updatedAt = new DateTime();
}
public function log(string $message): void
{
error_log("[Article] {$this->title}: $message");
}
}
魔術方法速查
| 方法 | 觸發時機 | 常見用途 |
| __construct | new 實例化 | 初始化、依賴注入 |
| __destruct | 物件銷毀 | 資源釋放、關閉連線 |
| __call / __callStatic | 呼叫不存在方法 | 動態代理、委派 |
| __get / __set / __isset / __unset | 存取不可見屬性 | 動態屬性、資料映射 |
| __toString | 物件當字串使用 | 輸出友善表示 |
| __invoke | 物件當函式呼叫 | Callable 物件、閉包替代 |
| __clone | clone 關鍵字 | 深拷貝控制 |
| __serialize / __unserialize | 序列化/反序列化 (PHP 7.4+) | 自訂序列化格式 |
| __debugInfo | var_dump/print_r | 控制除錯輸出內容 |
現代 PHP 最佳實務 (PHP 8.1+)
- 唯讀屬性:
public readonly string $id; (不可變物件)
- 建構子屬性提升:
public function __construct(public string $name) {}
- Enum 列舉型別:替代常數類別,提供型別安全
- Final/Readonly Class:
final readonly class DTO {} 防繼承與不可變
- 介面預設實作:
interface I { public function foo(): void { ... } }
- 嚴格型別:
declare(strict_types=1); 檔案首行強制型別檢查