1

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?

Kellen Stuart
  • 7,775
  • 7
  • 59
  • 82
  • 2
    Why don't you try it? But yes, $stmt will be defined by the `if` and remain defined for the rest of the function. – Marc B Dec 11 '15 at 20:37
  • @Marc B I tried, but the $stmt->error was not logging anything to my text file so I was suspicious. – Kellen Stuart Dec 11 '15 at 20:39

2 Answers2

4

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
Ian
  • 24,116
  • 22
  • 58
  • 96
1

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".

ranieribt
  • 1,280
  • 1
  • 15
  • 33