I'm a Java developer and recently I'v been tasked with PHP code review. While going through the PHP source code, I'v noticed that a variable is initialised in an if, while, switch and do statement then same variable is used outside these statements. Below is a fragment the code
Senario 1
if ($status == 200) {
$messageCode = "SC001";
}
// Here, use the $message variable that is declared in an if
$queryDb->selectStatusCode($message);
Senario 2
foreach ($value->children() as $k => $v) {
if ($k == "status") {
$messageCode = $v;
}
}
// Here, use the $messageCode variable that is declared in an foreach
$messageCode ....
In my understanding, a variable declared in a control statement is only accessible with in the control code block.
My question is, what is the variable scope of a variable in a PHP function and how is this variable accessible outside a control statement block?
How is that above code working and producing expected results?
In PHP control statements have no separate scope. They share the scope with the outer function or the global scope if no function is present. (PHP: Variable scope).
$foo = 'bar';
function foobar() {
$foo = 'baz';
// will output 'baz'
echo $foo;
}
// will output 'bar'
echo $foo;
Your variables will have the last value assigned within the control structure. It is good practice to initialize the variable before the control structure but it is not required.
// it is good practice to declare the variable before
// to avoid undefined variables. but it is not required.
$foo = 'bar';
if (true == false) {
$foo = 'baz';
}
// do something with $foo here
Namespaces do not affect variable scope. They only affect classes, interfaces, functions and constants (PHP: Namespaces Overview). The following code will output 'baz':
namespace A {
$foo = 'bar';
}
namespace B {
// namespace does not affect variables
// so previous value is overwritten
$foo = 'baz';
}
namespace {
// prints 'baz'
echo $foo;
}