switch statement without break

后端 未结 6 1502
粉色の甜心
粉色の甜心 2021-01-17 21:35

How come a case option in a switch statement that does not contain a break automatically forwards to a next case without check?

try {
    switch($param) {
          


        
6条回答
  •  借酒劲吻你
    2021-01-17 22:17

    In PHP 8 we have match, similar with switch expression but is significantly shorter:

    • it doesn't require a break statement
    • it can combine different arms into one using a comma
    • it returns a value, so you only have to assign value once

    An example:

    $message = match ($statusCode) {
        200, 300 => null,
        400 => 'not found',
        500 => 'server error',
        default => 'unknown status code',
    };
    

    Here's its switch equivalent:

    switch ($statusCode) {
        case 200:
        case 300:
            $message = null;
            break;
        case 400:
            $message = 'not found';
            break;
        case 500:
            $message = 'server error';
            break;
        default:
            $message = 'unknown status code';
            break;
    }
    

    reference : https://stitcher.io/blog/php-8-match-or-switch

提交回复
热议问题