Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP switch statement variable scope

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

For instance, take this hypothetical example:

$someVariable = 0;

switch($something) {

    case 1:
        $someVariable = 1;
        break;

    case 2:
        $someVariable = 2;
        break;
}

echo $someVariable;

Would this print 0 or 1/2?

like image 432
Philip Morton Avatar asked Feb 21 '10 15:02

Philip Morton


3 Answers

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.

like image 98
Pascal MARTIN Avatar answered Oct 16 '22 16:10

Pascal MARTIN


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.

like image 36
Gumbo Avatar answered Oct 16 '22 18:10

Gumbo


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

like image 27
codeholic Avatar answered Oct 16 '22 17:10

codeholic