Skip to content
Advertisement

PHP variable scope within Try/Catch block

In PHP, how do variable scope rules apply to Try/Catch blocks? Do variables declared within the try block go out of scope when the block has finished? Or are they in scope until the end of the function/method?

For example:

try
{
   // This may throw an exception when created!
   $o = new Pronk();
}
catch (Exception $ex)
{
   // Handle & exit somehow; not important here
   return false;
}

$o->doPronk();

Is this valid? Or should $o = NULL; be set before the try/catch to keep $o in scope?

(I know that the sample code does work, however I also know PHP can get a little stupid when it comes to scoping. My question is, ideally, how should it work? What is the correct and proper way to do this?)

Advertisement

Answer

Your code is valid. Variable scope in PHP is by function, not block. So you can assign a variable inside the try block, and access it outside, so long as they’re in the same function.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement