Is it a parser bug, or is there any usefulness in using curly brackets like this?
$x = 1;
{
$x++;
}
As far as I can see, it behaves exactly as if the brackets weren't there, so why is it valid syntax?
Is it a parser bug, or is there any usefulness in using curly brackets like this?
$x = 1;
{
$x++;
}
As far as I can see, it behaves exactly as if the brackets weren't there, so why is it valid syntax?
There is no any hidden meaning. It is more about readability.
Check manual:
Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement). Statements usually end with a semicolon. In addition, statements can be grouped into a statement-group by encapsulating a group of statements with curly braces. A statement-group is a statement by itself as well.
Its purpose is grouping operations for using in places where only one operation allowed.
if (cond) foo();
equals if (cond) { foo(); }
foo();
equals { foo(); }
Statements cannot be combined like expressions, you can always put a sequence of statements anywhere a statement can go by enclosing them in a set of curly braces.
{
$x++;
}
is just like
{$x++;}
which is just like
$x++;
They're to denote a block of code.
You can also consider this:
if (true) {
$x++;
}
The code has valid syntax, and it would behave exactly without the "if" condition. You can overcharge your code with "valid" and useless code as much as you want.
The curly brackets can be used to change the scope to a local scope. So if you define a variable in the brackets it won't be available outside the brackets