简体   繁体   中英

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?)

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.

I believe this is opinion based mostly. The code is correct and it will work as expected as long as the catch block always has the return statement. if the catch block does not return, the flow will continue and the code outside the try/catch block will be executed, and it will fail, because $o won't be initialized. You will be able to access $o because of the lack of block scope in php, but the method won't exist because the object construction failed.

the main concept for the exception handling is that if anything goes wrong inside the "try" block the code will enter into the "catch" block. so if

$o = new Pronk();

does not raise any error it will be in scope. we don't have to declare it before try/catch block. your code is perfectly valid.

As long as your obj is correctly constructed you can expect to use obj outside of try/catch block

However, suppose that there was an exception during construction. Then your obj wouldn't be even constructed inside try block. Therefore, you wouldn't be able to call the functions on obj because obj was not even created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM