Variable Shadowing

Variable shadowing is the confusion between variables of the same name, but of different context.

In PHP, this 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(), take 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() and catch(), which creates variables that actually overwrite existing ones, but are not perceived as such by a human coder

Such pattern sow confusion and lead to bugs. Given the context, the shadow may be intermittent: for example, a variable change content and type only when an exception is caught.

<?php

$x = 4;

function foo() {
    $x = 3;

    static $x; // No assignation, but $x is not NULL, on the first call

    global $x; // $x is not static anymore, and is 4

    $array = ['a', 'b', 'c'];
    try {
        foreach($array as $x) {
            echo $x;
        }
    } catch (Exception $x) {
        // $x becoms an exception, if it happens
    }

    // finally, $x becomes 5, stays global
    $x = 5;
}

foo();
echo $x;

?>

Documentation

Related : Variables, Close Naming