蓝色天空网mbsky.com · 知识 · 实践 · 创造PHP · 本地阅读预览
教程 / 后端开发 / PHP

PHP Switch

核对 PHP switch 多分支选择语句的求值机制、break 穿透控制、default 兜底行为,并与 PHP 8 严格比较表达式 match 实测对比。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

Switch 语句语法与工作原理

`switch` 语句适合围绕同一个表达式的多个离散取值选择代码块,相比冗长的 `elseif` 链结构更清晰。

结构由四部分组成:`expression` 是待求值的目标表达式,仅在进入 `switch` 时计算一次(本站实测辅助计数函数在匹配第三个 `case` 时仅被调用 `1` 次);`case value:` 逐项与表达式比对,命中后执行对应代码块;`break;` 用于及时跳出 `switch` 防止继续贯穿后续分支;可选的 `default:` 在所有 `case` 均未命中时兜底执行。

分支匹配、穿透控制与 PHP 8 match 对比

本站 PHP 8.4.27 实测多组场景:颜色分支对 `"red"`、`"blue"`、`"green"` 分别输出对应中文提示,对未列举的 `"yellow"` 落入 `default`。若省略 `break;`,命中 `case 1` 后会穿透执行 `case 2`(实测轨迹 `["one", "two"]`),此特性也常用于合并空 `case`(如 `case 'Sat': case 'Sun':` 共用 `weekend` 逻辑)。需注意 `switch` 采用松散比较 `==`(实测 `switch ('1')` 会先命中 `case 1:`),而 PHP 8 新增的 `match` 表达式采用严格比较 `===`、不发生穿透、可直接返回值,且未匹配又无 `default` 时抛出 `UnhandledMatchError`(实测 `match ('1')` 精确命中 `'1'` 分支,未匹配值 `99` 抛出 `UnhandledMatchError`)。

运行 PHP 8.4 switch 分支匹配、break 穿透与 match 严格对比实验

php · 阅读源码
<?php
declare(strict_types=1);

$cases = [];

// Case 1: switch multi-branch matching + default
$pickColor = static function (string $favcolor): string {
    switch ($favcolor) {
        case 'red':
            return '你喜欢的颜色是红色!';
        case 'blue':
            return '你喜欢的颜色是蓝色!';
        case 'green':
            return '你喜欢的颜色是绿色!';
        default:
            return '你喜欢的颜色不是 红, 蓝, 或绿色!';
    }
};
$c1Actual = [
    'red' => $pickColor('red'),
    'blue' => $pickColor('blue'),
    'green' => $pickColor('green'),
    'yellow' => $pickColor('yellow'),
];
$c1Expected = [
    'red' => '你喜欢的颜色是红色!',
    'blue' => '你喜欢的颜色是蓝色!',
    'green' => '你喜欢的颜色是绿色!',
    'yellow' => '你喜欢的颜色不是 红, 蓝, 或绿色!',
];
$cases[] = [
    'name' => 'switch_color_match_and_default',
    'passed' => $c1Actual === $c1Expected,
    'expected' => $c1Expected,
    'actual' => $c1Actual,
];

// Case 2: missing break fall-through vs intentional case grouping
$fallthrough = static function (int $step): array {
    $trace = [];
    switch ($step) {
        case 1:
            $trace[] = 'one';
        case 2:
            $trace[] = 'two';
            break;
        case 3:
            $trace[] = 'three';
            break;
    }
    return $trace;
};
$dayType = static function (string $day): string {
    switch ($day) {
        case 'Sat':
        case 'Sun':
            return 'weekend';
        default:
            return 'weekday';
    }
};
$c2Actual = [
    'fallthrough_1' => $fallthrough(1),
    'fallthrough_2' => $fallthrough(2),
    'sat' => $dayType('Sat'),
    'mon' => $dayType('Mon'),
];
$c2Expected = [
    'fallthrough_1' => ['one', 'two'],
    'fallthrough_2' => ['two'],
    'sat' => 'weekend',
    'mon' => 'weekday',
];
$cases[] = [
    'name' => 'switch_fallthrough_without_break',
    'passed' => $c2Actual === $c2Expected,
    'expected' => $c2Expected,
    'actual' => $c2Actual,
];

// Case 3: switch loose comparison (==) vs PHP 8 match strict comparison (===)
$switchClassify = static function (mixed $val): string {
    switch ($val) {
        case 1:
            return 'matched_int_1';
        case '1':
            return 'matched_str_1';
        default:
            return 'other';
    }
};
$matchClassify = static function (mixed $val): string {
    return match ($val) {
        1 => 'matched_int_1',
        '1' => 'matched_str_1',
        default => 'other',
    };
};
$unhandledCaught = false;
try {
    $_ = match (99) {
        1 => 'one',
    };
} catch (\UnhandledMatchError $e) {
    $unhandledCaught = true;
}
$c3Actual = [
    'switch_str_1' => $switchClassify('1'),
    'match_str_1' => $matchClassify('1'),
    'match_int_1' => $matchClassify(1),
    'match_unhandled_throws' => $unhandledCaught,
];
$c3Expected = [
    'switch_str_1' => 'matched_int_1',
    'match_str_1' => 'matched_str_1',
    'match_int_1' => 'matched_int_1',
    'match_unhandled_throws' => true,
];
$cases[] = [
    'name' => 'switch_loose_vs_match_strict',
    'passed' => $c3Actual === $c3Expected,
    'expected' => $c3Expected,
    'actual' => $c3Actual,
];

// Case 4: switch evaluates expression exactly once
$evalCount = 0;
$nextVal = static function () use (&$evalCount): string {
    $evalCount++;
    return 'green';
};
$matched = '';
switch ($nextVal()) {
    case 'red':
        $matched = 'r';
        break;
    case 'blue':
        $matched = 'b';
        break;
    case 'green':
        $matched = 'g';
        break;
}
$c4Actual = ['eval_count' => $evalCount, 'matched' => $matched];
$c4Expected = ['eval_count' => 1, 'matched' => 'g'];
$cases[] = [
    'name' => 'switch_expression_evaluated_once',
    'passed' => $c4Actual === $c4Expected,
    'expected' => $c4Expected,
    'actual' => $c4Actual,
];

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
预期结果 · 待实际运行核验
  • 核对 4 组颜色匹配与 default、无 break 穿透与合并 case、switch 松散比较与 PHP 8 match 严格比较及 UnhandledMatchError 抛出、以及 expression 仅求值 1 次。
运行 PHP 8.4 switch 分支匹配、break 穿透与 match 严格对比实验

所需环境:Windows x64、PHP 8.4 本地 CLI 环境。

当前源码 SHA256:107411f5d63a040f3dd4fd06872ea671b96004ca59c494870a78eed1794a570a

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载PHP Switch实验

所需环境:Windows x64、PHP 8.4 本地 CLI 环境。

ZIP SHA256:c42d7b6d364b613e4fcb618af7cbfff35c716e6cdf19f6f3f7eaa5d7b0db59bb

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

在 PHP 8 中,switch 语句与 match 表达式在比较方式、穿透行为和未命中处理上有何关键差异?

展开参考解答

switch 使用松散比较(==),省略 break 会向下穿透,未匹配且无 default 时静默跳过;match 使用严格比较(===),天然无穿透且作为表达式返回值,未匹配且无 default 时会抛出 UnhandledMatchError。

规范与官方依据