PHP8.0 match 用法排坑

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'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值