switch 是多值分支的經典結構,但 PHP 的鬆散比較 (==)、Fall-through 行為、continue 在 switch 中視同 break 等特性常造成 Bug。PHP 8.0 引入 match 運算式以嚴格比較、回傳值、無 Fall-through 解決歷史包袱。本文深度解析 switch 進階技巧、常見陷阱、match 遷移指南與實戰模式。
case 才開始執行。case/default 直到遇到 break/return/throw/腳本結束。==(鬆散),'5' == 5 為真。case 表達式只能是標量(整數、浮點數、字串),不可為陣列/物件(除非實作 __toString)。default 可放任意位置,建議最後。continue 在 switch 中等同 break;若在迴圈中需跳過外層迴圈,用 continue 2。<?php
$status = 201;
switch ($status) {
case 200:
case 201:
case 204:
$message = 'Success';
break;
case 400:
case 401:
case 403:
case 404:
$message = 'Client Error';
break;
case 500:
case 502:
case 503:
$message = 'Server Error';
break;
default:
$message = 'Unknown';
}
?>
<?php
function bytesToHuman(int $bytes): string {
$unit = '';
switch ($bytes) {
case $bytes >= 1024 * 1024 * 1024:
$bytes /= 1024 * 1024 * 1024;
$unit = 'GB';
// no break
case $bytes >= 1024 * 1024:
$bytes /= 1024 * 1024;
$unit = 'MB';
// no break
case $bytes >= 1024:
$bytes /= 1024;
$unit = 'KB';
// no break
default:
$unit = $unit ?: 'B';
}
return round($bytes, 2) . ' ' . $unit;
}
// 注意:此寫法依賴 Fall-through,極易誤改,建議改用 if/elseif 或 match
?>
⚠️ 警告:利用 Fall-through 做區間判斷屬於「聰明代碼」,維護極難。生產代碼請改用
match或if/elseif。
<?php
switch ($grade) {
case 'A':
case 'B':
case 'C':
$pass = true;
break;
case 'D':
case 'F':
$pass = false;
break;
}
?>
<?php
$input = '5'; // 字串
switch ($input) {
case 5: // 整數 5
echo "Matched integer 5\n"; // 執行!
break;
case '5':
echo "Matched string '5'\n";
break;
}
// 輸出:Matched integer 5
// 原因:switch 使用 == 比較,'5' == 5 為 true
// 且 case 5 寫在前面,優先匹配
?>
<?php
// 1. 強制轉型
switch ((string)$input) {
case '5': ...
}
// 2. PHP 8.0+ 使用 match(嚴格 ===)
$message = match ((string)$input) {
'5' => 'five',
default => 'other',
};
// 3. 明確型別檢查
if (is_int($input)) { /* ... */ }
?>
| 特性 | switch | match |
|---|---|---|
| 比較運算子 | == (鬆散) | === (嚴格) |
| 回傳值 | 無 (需自行賦值) | 有 (運算式) |
| Fall-through | 有 | 無 |
| break 需求 | 必要 | 不需要 |
| 窮盡檢查 | 無 | 有 (未涵蓋拋 UnhandledMatchError) |
| 多值合併 | 連續 case | 逗號分隔 case 1, 2: |
| 預設分支 | default: | default => |
<?php
$httpCode = 404;
$message = match ($httpCode) {
200, 201, 204 => 'Success',
400 => 'Bad Request',
401 => 'Unauthorized',
403 => 'Forbidden',
404 => 'Not Found',
500, 502, 503 => 'Server Error',
default => 'Unknown Status',
};
echo $message; // Not Found
// 複雜條件:match(true)
$age = 25;
$category = match (true) {
$age < 13 => 'Child',
$age < 20 => 'Teenager',
$age < 65 => 'Adult',
default => 'Senior',
};
?>
<?php
function nextOrderStatus(string $current, string $action): string {
return match ("$current:$action") {
'pending:pay' => 'paid',
'paid:ship' => 'shipped',
'shipped:deliver' => 'delivered',
'delivered:review' => 'completed',
'pending:cancel',
'paid:refund' => 'cancelled',
default => throw new InvalidTransitionException(
"Invalid transition: $current -> $action"
),
};
}
?>
<?php
interface PaymentGateway {
public function charge(float $amount): ChargeResult;
}
$gateway = match ($order->payment_method) {
'credit_card' => new StripeGateway($config),
'paypal' => new PayPalGateway($config),
'bank_transfer' => new BankGateway($config),
default => throw new UnsupportedPaymentMethod($order->payment_method),
};
$result = $gateway->charge($order->total);
?>
<?php
// Before
if ($user->isAdmin()) { return 'admin'; }
elseif ($user->isEditor()) { return 'editor'; }
elseif ($user->isAuthor()) { return 'author'; }
else { return 'guest'; }
// After (PHP 8.0+)
return match (true) {
$user->isAdmin() => 'admin',
$user->isEditor() => 'editor',
$user->isAuthor() => 'author',
default => 'guest',
};
?>
| 結構 | 百萬次迴圈耗時 | 備註 |
|---|---|---|
| switch (鬆散比較) | 0.45s | 基準 |
| match (嚴格比較) | 0.42s | 略快,JIT 優化更好 |
| if/elseif 鏈 (5 條件) | 0.55s | 線性搜尋 |
switch ($x) { case A: ... } 改為 match ($x) { A => ... }。case 值型別,確保與 $x 型別一致(嚴格比較)。break。default: 改為 default =>。match(true) 或 if/elseif。default => throw new \UnhandledMatchError() 確保窮盡。switch 是 C 遺產,match 是現代 PHP 的表達式導向分支。新專案預設用 match,舊代碼逐步遷移。記住:嚴格比較避免型別陷阱、回傳值支援函式式風格、窮盡檢查捕獲漏案、無 Fall-through 減少 Bug。將 match 寫入團隊 Coding Standard,讓分支邏輯更安全、更易讀。