萬盛學電腦網

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

PHP switch 進階用法完全指南:Fall-through 技巧、match 運算式、型別比較陷阱與實戰模式

前言

switch 是多值分支的經典結構,但 PHP 的鬆散比較 (==)、Fall-through 行為、continue 在 switch 中視同 break 等特性常造成 Bug。PHP 8.0 引入 match 運算式以嚴格比較、回傳值、無 Fall-through 解決歷史包袱。本文深度解析 switch 進階技巧、常見陷阱、match 遷移指南與實戰模式。

一、switch 核心機制與執行流程

關鍵規則

  1. 逐行執行:從第一行開始,直到匹配 case 才開始執行。
  2. Fall-through:執行後續 case/default 直到遇到 break/return/throw/腳本結束。
  3. 比較運算子:==(鬆散),'5' == 5 為真。
  4. case 表達式只能是標量(整數、浮點數、字串),不可為陣列/物件(除非實作 __toString)。
  5. default 可放任意位置,建議最後。
  6. continue 在 switch 中等同 break;若在迴圈中需跳過外層迴圈,用 continue 2。

二、Fall-through 進階技巧(有意圖的穿透)

1. 多值共用邏輯

<?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';
}
?>

2. 區間/範圍判斷(利用無 break 累加)

<?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。

3. 空 case 分組

<?php
switch ($grade) {
    case 'A':
    case 'B':
    case 'C':
        $pass = true;
        break;
    case 'D':
    case 'F':
        $pass = false;
        break;
}
?>

三、型別比較陷阱:為什麼 '5' 能匹配 case 5?

<?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)) { /* ... */ }
?>

四、match 運算式(PHP 8.0+):現代替代方案

特性switchmatch
比較運算子== (鬆散)=== (嚴格)
回傳值無 (需自行賦值)有 (運算式)
Fall-through有無
break 需求必要不需要
窮盡檢查無有 (未涵蓋拋 UnhandledMatchError)
多值合併連續 case逗號分隔 case 1, 2:
預設分支default:default =>

match 實戰範例

<?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',
};
?>

五、實戰模式:回傳值、提前返回、狀態機

1. 狀態機:訂單狀態流轉

<?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"
        ),
    };
}
?>

2. 策略模式分發

<?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);
?>

3. 替換巢狀 if/elseif

<?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 → match

  1. 將 switch ($x) { case A: ... } 改為 match ($x) { A => ... }。
  2. 檢查所有 case 值型別,確保與 $x 型別一致(嚴格比較)。
  3. 移除所有 break。
  4. 將 default: 改為 default =>。
  5. 若原本依賴 Fall-through,重構為 match(true) 或 if/elseif。
  6. 加上 default => throw new \UnhandledMatchError() 確保窮盡。

結語

switch 是 C 遺產,match 是現代 PHP 的表達式導向分支。新專案預設用 match,舊代碼逐步遷移。記住:嚴格比較避免型別陷阱、回傳值支援函式式風格、窮盡檢查捕獲漏案、無 Fall-through 減少 Bug。將 match 寫入團隊 Coding Standard,讓分支邏輯更安全、更易讀。

copyright © 萬盛學電腦網 all rights reserved