PHP switch statement variable scope

前端 未结 4 1331
耶瑟儿~
耶瑟儿~ 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:47

    PHP does only have a global and function/method scope. So $someVariable inside the switch block refers to the same variable as outside.

    But since $something is not defined (at least not in the code you provided), accessing it raises a Undefined variable notice, none of the cases match (undefined variables equal null), $someVariable will stay unchanged and 0 will be printed out.

提交回复
热议问题