8.5的新的流语句match表达式

admin 2026-03-06 8 阅读 0 评论

8.5的新的流语句match,还蛮好用的,比switch更加实用简洁容易维护了

 'OK',
    404 => 'Not Found',
    500 => 'Server Error',
    default => 'Unknown Status',
};

echo $message; // 输出: Not Found

多条件匹配

 ['create', 'read', 'update', 'delete', 'manage-users'],
    'editor', 'author' => ['create', 'read', 'update'],
    'subscriber' => ['read'],
    default => ['login']
};

print_r($permissions);
// 输出: Array ( [0] => create [1] => read [2] => update )

与枚举结合使用

 '订单待支付',
            OrderStatus::Paid => '支付成功,准备发货',
            OrderStatus::Shipped => '商品已发货',
            OrderStatus::Delivered => '订单已完成',
            OrderStatus::Cancelled => '订单已取消'
        };
    }
}

$orderService = new OrderService();
echo $orderService->getStatusMessage(OrderStatus::Paid); 
// 输出: 支付成功,准备发货

对比下传统switch语句

是不是更加强大了

 

 

登录 / 注册 评论!