Try ... catch block does not limit scope

This isn’t really a question, just something I wanted to share in case others may have been wondering the same thing.

Usually ‘{’ and ‘}’ are considered to define scope of a variable (I come from a C++ world), and I had been assuming that PHP does the same. Today I came across the situation where I had instantiated a variable inside a try {…} catch block, but I needed to use the variable outside of the block.

A quick test determined that try {…} catch does in fact not limit the scope of variables.

	$var = "my var";
catch(Exception $r_error)

print("|" . $var . "|");

scope in PHP is at the function/method level.

My thoughts as well. Wasn’t sure if try {…} catch was implemented as a function or method.

PS: Perhaps this should have been posted in the PHP forum? Sorry if I mis-posted, feel free to move.

Yeah … The weirdest thing is that you can use block-scope syntax in you PHP-code. This would make you assume that scope behaves like in C/C++. Only it doesn’t. The following is syntactically legal, but the curly braces are just ignored by the interpreter. Odd.

function foo() {
  $bar = 4;
    $bar = 8;
  echo $bar; // echoes 8 ... not 4 as one might expect ...