Search code examples
phpcurly-braces

Use curly brackets to structure code in PHP


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.


Solution

  • 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;
    }