phpscopelanguage-construct

PHP Declarator In If-Statement Scope


This is pretty basic. Let's say you define a variable in an if statement

if($stmt = $db->prepare($sql)) {
   // do stuff
}

Can I access $stmt below the if statement? Or does $stmt need to be defined above the if?


Solution

  • PHP does not have block level scope, only function level scope. $stmt will be available anywhere below that if statement (in and out of the if).

    Something to keep in mind however, if you define new variables inside the if block, will only exist if that if evaluates to true.

    Eg:

    <?php
    $var1 = true;
    if ($var2 = false) { 
        $var3 = true; // this does not get executed
    } else {
        $var4 = 5;
    }
    var_dump($var1); // true
    var_dump($var2); // false
    var_dump($var3); // ERROR - undefined variable $var3
    var_dump($var4); // 5