PHP switch statement variable scope
Asked Answered
T

5

5

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?

Talavera answered 21/2, 2010 at 15:0 Comment(1)
Why don’t you just try it?Reckon
H
8

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.

Hanse answered 21/2, 2010 at 15:2 Comment(1)
Even if PHP had lexical scope, $someVariable would still be accessible in the switch block.Arundinaceous
R
6

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.

Reckon answered 21/2, 2010 at 15:12 Comment(0)
H
1

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

Hakluyt answered 21/2, 2010 at 15:2 Comment(0)
A
1

It will print 1 or 2 if you change the value of $someVariable in the switch statement, and 0 if you don't.

Arundinaceous answered 21/2, 2010 at 15:3 Comment(0)
D
-1

To give you a universally-correct answer, we would need to know the value of $something.

If we took your code at face value, $something would be undefined....and since there is no "default" case, $someVariable would just stay 0.

If $something was 1, $someVariable would be 1.

If $something was 2, $someVariable would be 2.

Deina answered 10/8, 2023 at 18:28 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Orthogenesis

© 2022 - 2024 — McMap. All rights reserved.