Search the blog

Assuming you’re not using global or static variables, variable scope in PHP applies to files, methods and functions. Because functions are wrapped in { and } you may think that try, catch and finally blocks use the same variable scope as functions and methods since they too are enclosed in curly brackets. However, that is not the case, as is demonstrated by the code below.

try {

    // No exception thrown

} catch (Exception $e) {

    // For demo only

}

var_dump(isset($e)); // false

try {

    // Exception thrown
    throw new Exception('error');

} catch (Exception $e) {

    // For demo only

}

var_dump(isset($e)); // true

Even though the catch block above looks syntactically like a function the same variable scope does not apply. If catch is called then $e becomes part of the local scope.

This applies to finally blocks too.

Tim Bennett is a web designer and developer. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.