PHP switch statement variable scope

前端 未结 4 1332
耶瑟儿~
耶瑟儿~ 2021-01-03 00:51

In PHP, how is variable scope handled in switch statements?

For instance, take this hypothetical example:

$someVariable = 0;

switch($something) {

          


        
4条回答
  •  太阳男子
    2021-01-03 01:52

    The variable will be the same in your whole portion of code : there is not variable scope "per block" in PHP.

    So, if $something is 1 or 2, so you enter in one of the case of the switch, your code would output 1 or 2.

    On the other hand, if $something is not 1 nor 2 (for instance, if it's considered as 0, which is the case with the code you posted, as it's not initialized to anything), you will not enter in any of the case block ; and the code will output 0.

提交回复
热议问题