default as first option in switch statement?

前端 未结 9 1795
后悔当初
后悔当初 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.

    0 讨论(0)
  • 2020-12-02 00:28

    It looks odd for the same reason that

    else {
       echo "lol";
    }
    if (1 == 1) {
       echo "bbq";
    }
    

    would look odd, if it were valid. If for this reason alone I'd avoid it.

    In addition, you know that every time you show the code to somebody, you're going to have to explain that putting the default case first was deliberate; this is usually a sign that it's not a great idea.

    0 讨论(0)
  • 2020-12-02 00:29

    I'd personally prefer to do

    switch($kind)
    {
        case 'kind2':
            // do some stuff for kind2 here
            break;
    
        // [...]
    
        case 'kindn':
            // do some stuff for kindn here
            break;
    
        case 'kind1':
        default:
            $kind = 'kind1'; // Redundant if it's already set as 'kind1', but that doesn't make any difference to the code.
            // Do some stuff for kind 1 here
            break;
    
    }
    
    0 讨论(0)
提交回复
热议问题