default as first option in switch statement?

前端 未结 9 1806
后悔当初
后悔当初 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:14

    In case anybody find this page through google as I did:

    I was wondering the same thing as Josh - so... One thing is standards, which I think we should all try harder to adhere too, but another thing is hacking (in the: exploit-every-possibility kinda way).

    While it's ugly/weird/not normal - it IS possible and IMHO could be useful in some rare cases...

    Consider the following:

    $color = "greenish";
    //$color = "green";
    
    switch($color) {
        default:
            echo "no colors were selected so the color is: ";
        case "red":
            echo "red
    \n"; break; case "blue": echo "blue
    \n"; break; case "green": echo "green
    \n"; break; }

    If $color = "greenish"; the code will print

    no colors were selected so the color is red

    while if $color = "green"; or any other defined cases, it will just print the color.

    It know it not the best example, but you get the point ;) Hope it helps somebody.

提交回复
热议问题