26

Is it possible to enclose code fragments in PHP within brackets (without using the fragment as a function)?

Would the following code behave the same way as it would without the curly brackets? Or might there be any problems depending on what kind of code used inside or outside the brackets?

For example, will this:

<?php

// First Code-Block
{# several lines of code
}

// Second Code-Block
{# another several lines of code
}

?>

Always behave the same way as this:

<?php

// First Code-Block
# several lines of code

// Second Code-Block
# another several lines of code

?>

Update: One of the goals, as stated in "My1"'s comment as well, is to structure large code sections. Especially since most IDEs give you the option to collapse the lines between the brackets.

Especially in consideration of "dragondreamer"'s "Luke Mills"'s answers I played around with it a bit, and so far I didn't encounter any side effects. Of course, this might change with new PHP Versions in the future but "Luke Mills"'s answer gives good pointers on what to keep an eye on.

Albin
  • 1,000
  • 1
  • 11
  • 33
  • You mean, without something like `if(true) { ... }`? For what purpose? – quietmint Feb 20 '13 at 02:06
  • I would really like to see this implement a way for us to manage garbage collection by wrapping part of the code up that safely can be collected once the segment/statement is done. – superhero Oct 09 '15 at 09:43
  • 4
    it really helps when you have large sections of code and scrolling gets a hassle over time when you have an editor that allows you to "collapse" the block, making it easier to focus on the code you are about right now – My1 Nov 13 '16 at 21:24

4 Answers4

35

Yes, but it won't create a new local scope. It's not something that would normally be done. Usually people mark blocks like this with comments.

Update:

It took a bit of digging to find a reference to it in the manual, but here it is:

http://www.php.net/manual/en/control-structures.intro.php

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. The various statement types are described in this chapter.

The key here is statements can be grouped into a statement-group by encapsulating a group of statements with curly braces.

I also had a look for a reference to variable scope as it relates to this situation, but the manual doesn't specifically mention it, however you can think of it like this:

In PHP, functions and classes create a variable scope. You can read about that here. But a statement-group (as described above) does not. Don't think of the curly braces of a statement-group like the function (or class) wrapping brackets, but think of them like the curly braces that wrap the statement-group of control structures (if, for, while, switch, etc.) - because that's exactly what they are. It's clear that if you're using an if statement (or any other control structure) that the braces don't introduce a new scope, they are simply wrappers for a block of statements.

Luke Mills
  • 1,616
  • 1
  • 11
  • 18
  • 1
    Yeah i cant think of a single good reason to do this. If it doesnt functionally require `{}` (like control structures, functions, etc..) then it seems silly and confusing to do it. – prodigitalson Feb 20 '13 at 02:10
  • 1
    @Luke Mill: Thanks, where can I find this Information in a PHP reference (I was looking for ages before I asked)? – Albin Feb 20 '13 at 04:33
  • 5
    @prodigitalson: Reason: I have to use a code editor with native settings (notepad++) which only colapses comment-blocks (*/ /*) and functional-block ({}). – Albin Feb 20 '13 at 04:35
  • @Stackoverflow2000, I've updated the answer with additional info. HTH. – Luke Mills Feb 20 '13 at 07:06
  • 5
    @Stackoverflow2000: Well of all the reasons - "so i can get code folding in my editor" - has to be the worst... – prodigitalson Feb 20 '13 at 13:53
  • 1
    @Luke Mills: thanks, never thought of looking into the "introduction", thought that curly brackets will have a specification for itself somewhere, so I tried to find them as an indevidual entry in a command-reference. – Albin Feb 21 '13 at 06:21
  • 12
    @prodigitalson, well I you dont use code-colapsing, yes, I suppose it's a "bad reason". But if you need it and can't choose your editor it's important to have an alterantive. (PS. as long as you dont offer to do my work for me, please refrain from judging my reasons by standards that apply to your **personal** work) – Albin Feb 21 '13 at 06:46
  • and to create a new scope with a function http://stackoverflow.com/a/33460057/3160597 – azerafati Nov 01 '15 at 07:23
  • 5
    FWIW I just tried this myself (before arriving here) because I thought it might prove useful to get around the problem that /* \*/ style comments cannot be nested. Using curly braces I can define a block of code and put a comment at the top. All IDEs will let you find the pair to a given brace to it makes it easy to find where the comment no longer applies rather than the unhelpful /* ENDS */ or similar which would be even harder to parse with nested commented blocks. Seems useful to me for that reason. – ThisLeeNoble Jul 29 '16 at 13:05
  • I have a 900-line function that is very difficult to understand or refactor. Wrapping some sections with `{}` and adding a one-line comment allows me to collapse blocks. This helps me to understand the code, so it is now at least possible for me to maintain it. Later, I may identify sections that I could refactor into separate functions. – Liam Sep 01 '23 at 23:10
11

PHP code behavior does not change if you enclose it within curly brackets. However, you can't use some PHP statements inside curly brackets:

  • namespace declarations;
  • namespace use declarations to alias or import any names;
  • global const declarations;
  • __halt_compiler().

This means, the following script will work:

<?php
const x = 5;
echo x;

but the following will not compile:

<?php
{
  const x = 5;
  echo x;
}
dragondreamer
  • 208
  • 3
  • 8
5

In one project I'm working on, I use statement-groups to indicate structure - in my case, parent/child relationships between nodes creates in a router:

$router = new Router();

$admin = $router->route('admin');
{
    $upload = $admin->route('upload')->post('upload');

    $menu = $admin->route('menu');
    {
        $menu->route('load')->get('load');
        $menu->route('save')->get('save');
    }
}

```

Internally, this builds a hierarchical structure like:

/admin
  /upload
  /menu
    /load
    /save

Calling route() in this example creates a child - so the code creates a model (inside the router) which has a tree structure, but the structure of the code does not reflect that.

I'm using curly braces here to make the code more legible, since reading the code without curly braces and indentation would be quite difficult:

$router = new Router();

$admin = $router->route('admin');
$upload = $admin->route('upload')->post('upload');
$menu = $admin->route('menu');
$menu->route('load')->get('load');
$menu->route('save')->get('save');

Indentation in this case really clarifies what's happening, I think.

mindplay.dk
  • 7,085
  • 3
  • 44
  • 54
1

I also do this, solely because of my text editor (Komodo Edit 8.5). It's not a "bad reason" or "bad coding", if it helps you and doesn't cause any problems and if there's no other easy way to do it.

I solve the problem with a work-around:

if(1 == 1){ //always executing if function
//whatever you want to add
}
#

adding a # at the end prevents my editor from collapsing all empty lines below the curly brackets. This helps to further structure the code.

g35232t54
  • 37
  • 1
  • 7