您可以在 PHP 8.0+ 中使用 match statements 完成此操作。
如果您的 switch 语句中只有一个表达式,则它等效于以下 match 语句。请注意,与 switch 语句不同,我们可以选择返回一个变量(在这段代码中,我将结果存储在 $result 中)。
$test = 0.05;
$result = match (true) {
$test < 0.1 => "I'm less than 0.1",
$test < 0.01 => "I'm less than 0.01",
default => "default",
};
var_dump($result);
Match 仅允许您在右侧有一个表达式(=> 之后的所有内容)。与多行 case 的 switch 语句等效的是使用单独的函数。
function tinyCase(){}
function veryTinyCase(){}
function defaultCase(){}
$test = 0.01;
match (true) {
$test < 0.1 => tinyCase(),
$test < 0.1 => veryTinyCase(),
default => defaultCase(),
};
作为参考,如果你只是想检查是否相等,你可以这样做:
$result = match ($test) { // This example shows doing something other than match(true)
0.1 => "I'm equal to 0.1",
0.01 => "I'm equal to 0.01",
default => "default",
};
Match 语句与 switch 语句确实有一些您需要注意的关键区别:
- 我的最后一个示例将使用严格的相等检查
=== 而不是松散的 ==。
- 如果未提供默认情况,则在没有匹配项时会引发 UnhandledMatchError 错误。
- 如果您忘记添加
break,也不用担心会进入下一个案例。