Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP variable scope within Try/Catch block

Tags:

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

like image 393
DOOManiac Avatar asked Sep 09 '15 20:09

DOOManiac


People also ask

Can you access variables from TRY in catch?

So, if you declare a variable in try block, (for that matter in any block) it will be local to that particular block, the life time of the variable expires after the execution of the block. Therefore, you cannot access any variable declared in a block, outside it.

Do try catch blocks have scope?

Variables declared within the try/catch block are not in scope in the containing block, for the same reason that all other variable declarations are local to the scope in which they occur: That's how the specification defines it. :-) (More below, including a reply to your comment.)

Can I use try catch inside try catch in PHP?

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

Are nested try catches bad?

I actually don't think there's anything inherently wrong about nested Try / Catch blocks, except that they can be difficult to navigate and are likely a sign that you could do some refactoring (the inner Try / Catch into its own method, for example).


2 Answers

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.

like image 179
Barmar Avatar answered Sep 23 '22 05:09

Barmar


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.

like image 36
taxicala Avatar answered Sep 20 '22 05:09

taxicala