match 是 PHP 8 中新加入的一种语句,用于执行类似 switch 语句的操作。在 PHP 8 之前,switch 语句只能使用简单的比较操作,而 match 语句则提供了一种更灵活的方式来进行条件匹配。
match 语句使用方式如下:
$result = match ($value) {
1 => 'one',
2 => 'two',
3 => 'three',
default => 'not one, two, or three',
};
如果需要用到or条件的话:
$result = match ($value) {
1,2 => 'one or two',
3 => 'three',
default => 'not one, two, or three',
};
需要注意的一点是,如果 value是字符串类型,条件中的1,2都必须是字符串类型,也就是value 的类型必须要与条件中的一致:
$value = '1';
//这样的话下面的条件必须是字符串, 不然就会一直输出default 值
$result = match ($value) {
'1','2' => 'one or two',
'3' => 'three',
default => 'not one, two, or three',
};
另外,如果你的比较条件中包含了表达式,需要确保对表达式使用圆括号来分组,以避免语法错误。比如:
$num = 3;
$result = match ($num) {
1 => 'one',
2 => 'two',
(2+1) => 'three',
default => 'not one, two, or three',
};
echo $result; // 输出 'three'