default as first option in switch statement?

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

    Other answers give good examples of it, just stating for clarity's sake...

    A Case (including default) does not stop executing at its end unless you include a break. Although switch is often compared to a sequence of if elseif elseif etc., however it's not quite that.

    Short version: SWITCH/CASE only acts like IF/ELSEIF/ELSE if you include breaks after each case. SWITCH/CASE is more like a series of "if" statements where each has the same variable check with a different value it's being checked against.

    Long version: Without including a break, each case is a "start here"and the differences in a lot of ways make it closer to GOTO without the drawbacks. Technically, if you really REALLY wanted to (read, were a masochistic coder who wanted to really challenge themselves) you could write almost any procedural programs using only one external array, a for loop, and a switch nested inside.

    Seriously, why you would want to do this boggles my mind, but it really demonstrates how far switch/case can deviate from if/elseif patterns, so it's here for you for academic reasons (but don't do it!)...

    $array = [];
    $array['masterLoop'] = 1;
    $for ($i = 0, $i < $array['masterLoop'], $i++ ){
        switch($array['goto']){
            default: 
            case 1: 
                PRINT: "Welcome to the program";
            case 2: 
                PRINT: "Please make a choice:";
            case 3:
                $array['choice']='';
                // Wait for some input variable and set choice to it.
            case 4: 
                $array['goto']=$array['choice'];
                $array['masterLoop']++;
        }
    }
    

    The way this code would run (after you set up something for capturing and setting a choice) would be it'd start up with

    "Welcome to the program. Please make a choice."
    <>
    "Please make a choice."
    <>
    "Welcome to the program. Please make a choice."
    <>
    // program awaits user input
    <>
    // user triggers infinite loop
    

    So... you can use switches to reflect back to the days of BASIC... but if you do and I have to debug your code later after you wrote it all like that... May Linus Torvalds mercy on your soul.

提交回复
热议问题