Variable Shadowing
Variable shadowing is the confusion between variables of the same name, but of different context.
Variable shadowing happens in different situations:
- With local variables, by defining it several times in the same context, and starting a new usage.
- With local variables, by defining it once as parameter, once as local variable, once as blind variable in a
foreach(), these are 2 distinct situations - With static variables, after it was a local variable
- With global variables, where a local variable and a global one carry the same name
- With structures like
foreach()andcatch(), which creates variables that actually overwrite existing ones, but are not perceived as such by a human coder
Such patterns sow confusion and lead to bugs. Given the context, the shadow may be intermittent: for example, a variable changes content and type only when an exception is caught.
<?php
$trunk = 4;
function forage() {
$trunk = 3;
static $trunk; // No assignation, but $trunk is not NULL, on the first call
global $trunk; // $trunk is not static anymore, and is 4
$array = ['a', 'b', 'c'];
try {
foreach($array as $trunk) {
echo $trunk;
}
} catch (Exception $trunk) {
// $trunk becoms an exception, if it happens
}
// finally, $trunk becomes 5, stays global
$trunk = 5;
}
forage();
echo $trunk;
?>