default as first option in switch statement?

前端 未结 9 1826
后悔当初
后悔当初 2020-12-01 23:58

I\'ve tested this and it works fine, but it looks... weird... to me. Should I be concerned that this is nonstandard form which will be dropped in a future version of PHP, or

9条回答
  •  盖世英雄少女心
    2020-12-02 00:24

    This can be really handy for flow control, particularly if you aren't breaking between cases.

    For example:

    $step = $_GET['skip_to_step'];
    switch($step) {
        default:
        case 'step1':
            // do some stuff for step one
        case 'step2':
            // this follows on from step 1 or you can skip straight to it
    }
    

    You could add in an additional 'if', or a clever 'or' to make $step default to 'step1' before you start the switch but that's just extra code, reducing readability.

提交回复
热议问题