PHP switch statement variable scope

In PHP, how is a variable region handled in switch statements?

For example, take this hypothetical example:

$someVariable = 0; switch($something) { case 1: $someVariable = 1; break; case 2: $someVariable = 2; break; } echo $someVariable; 

Will it print 0 or 1/2?

+4
source share
4 answers

The variable will be the same throughout your part of the code: in PHP, there is no "per block" variable scope.

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

On the other hand, if $something not 1 and 2 (for example, if it is treated as 0 , which is the case with the code you sent, since it is not initialized by anything), you will not enter any of the case blocks; and the code will output 0 .

+6
source

PHP has only global and functional / scope method . Thus, $someVariable inside the switch block refers to the same variable as the outside.

But since $something not defined (at least not in the code you specified), access to it causes the Undefined variable to be notified, none of the cases match (undefined variables are null ), $someVariable will remain unchanged and 0 will be printed .

+5
source

It will print 1 or 2. Variables in PHP have the scope of the entire function.

+1
source

It will print 1 or 2 if you change the value of $someVariable in the switch statement and 0 if you do not.

+1
source

Source: https://habr.com/ru/post/1301952/


All Articles