4

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?

arogachev
  • 33,150
  • 7
  • 114
  • 117
Edson Medina
  • 9,862
  • 3
  • 40
  • 51
  • 2
    It defines a block of code. If you put an `if ($condition)` on top of it, the whole block will be executed if the *condition* is true instead of only the first expression. – Hkan Sep 17 '15 at 10:00
  • 1
    See also the abstract on [statements and grouping in the manual](http://php.net/manual/en/control-structures.intro.php). – mario Sep 17 '15 at 10:02

5 Answers5

7

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.

Pawel Gumiela
  • 1,992
  • 2
  • 20
  • 36
2

Its purpose is grouping operations for using in places where only one operation allowed.

if (cond) foo(); equals if (cond) { foo(); }
foo(); equals { foo(); }

vp_arth
  • 14,461
  • 4
  • 37
  • 66
2

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.

  • Curly brackets are used to mark class, function (methods in OOP terminology), loop and control structure bodies.
  • They can also be used within strings to separate variables from surrounding text.
Saket Mittal
  • 3,726
  • 3
  • 29
  • 49
0
{
$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.

Amarnasan
  • 14,939
  • 5
  • 33
  • 37
-2

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

  • 4
    Only functions and methods have their own, local scope. – vp_arth Sep 17 '15 at 10:05
  • This was posted as an answer, but it does not attempt to answer the question. It should possibly be an edit, a comment, another question, or deleted altogether. – Saket Mittal Sep 18 '15 at 07:41