PHP 简明教程

PHP match 表达式

1. PHP match 表达式

match 表达式提供了一种处理多个条件检查的新方法(类似于 switch 语句)。

match 表达式会将给定的表达式与多个备选方案进行计算(使用严格比较),并返回一个值。

提示: match 表达式是 PHP 8.0 中引入的新特性。

以下是 matchswitch 之间的主要区别:

  • match 表达式的语法比 switch 更具可读性。
  • match 表达式会返回一个值,而 switch 不会直接返回。
  • match 表达式在匹配成功后会自动跳出(break),而 switch 则必须显式地编写 break; 语句。
  • match 表达式使用的是严格比较(===),而 switch 使用的是宽松比较(==)。

1.1 match 的语法

$result = match($expression) {
  condition1 => returnvalue1,
  condition2 => returnvalue2,
  condition3, condition4 => returnvalue3,
  default => defaultvalue,
}

提示: default 分支(arm)用于捕获所有未被匹配的表达式。

下面的示例与我们在 switch 教程页面中看到的功能相同,但这里我们使用了 match 表达式:

示例

$favcolor = "red";

$text = match($favcolor) {
  "red" => "Your favorite color is red!",
  "blue" => "Your favorite color is blue!",
  "green" => "Your favorite color is green!",
  default => "Your favorite color is neither red, blue, nor green!",
};

echo $text;

2. 匹配多个值

如果您希望 match 表达式让多个值对应相同的代码块(返回值),可以使用逗号将它们分组组合在一起:

示例

匹配多个值:

$d = 3;

$text = match($d) {
  1, 2, 3, 4, 5 => "The week feels so long!",
  6, 0 => "Weekends are best!",
  default => "Invalid day",
};

echo $text;

3. default 关键字

match 表达式中,必须包含一个能够匹配该表达式的条件,或者包含一个 default 分支来处理未匹配的情况。

如果没有任何条件匹配成功,并且也没有提供 default 默认分支,那么 match 表达式将抛出 UnhandledMatchError 异常。

示例

以下代码将抛出 UnhandledMatchError 异常:

$favcolor = "pink"; // 没有条件可以匹配这个值

try {
  $text = match($favcolor) {
    "red" => "Your favorite color is red!",
    "blue" => "Your favorite color is blue!",
    "green" => "Your favorite color is green!",
  };
} catch (\UnhandledMatchError $e) {
  var_dump($e);
}

echo $text;