PHP Declarator In If-Statement Scope

59 Views Asked by At

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?

2

There are 2 best solutions below

1
Ian On BEST ANSWER

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
0
ranieribt On

Pretty basic test:

if ($stmt = 5) {
    var_dump($stmt);
}

var_dump($stmt);

Outputs:

int(5)
int(5)

Yes, You can "access $stmt below the if statement".