Use Curly Brackets to Structure Code in PHP

Use curly brackets to structure code in PHP

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

What's the purpose of separate curly brackets in PHP

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

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

Three curly brackets together in php source code

They are vim fold markers, they make it easy to collapse and expand the text inbetween the triple curly braces in vim, in the example shown alternating between:

...

/* {{{ proto bool ctype_digit(mixed c)
Checks for numeric character(s) */
static PHP_FUNCTION(ctype_digit)
{
CTYPE(isdigit);
}
/* }}} */

...

and just

...

/* {{{ proto bool ctype_digit(mixed c)

...

If you look at the end of the file where you find them, you'll often find a block like this:

/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/

Which is another more-obvious indicator that these comments relate to vim.

PHP: Add optional curly braces to control structures in existing code

You can use token_get_all to build an AST, loop over the tokens, and add the braces in. From that you should be able to save back out the amended source file.

There's also the, excellent, PHP_Parser library too.

Curly braces in string in PHP

This is the complex (curly) syntax for string interpolation. From the manual:

Complex (curly) syntax


This isn't called complex because the syntax is complex, but because
it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string
representation can be included via this syntax. Simply write the
expression the same way as it would appear outside the string, and
then wrap it in { and }. Since { can not be escaped, this syntax
will only be recognised when the $ immediately follows the {. Use
{\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad.";

// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";

// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}";

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

Often, this syntax is unnecessary. For example, this:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

behaves exactly the same as this:

$out = "{$a} {$a}"; // same

So the curly braces are unnecessary. But this:

$out = "$aefgh";

will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

$out = "${a}efgh"; // or
$out = "{$a}efgh";

In php, should curly brackets be used even in short conditional statements?

I have seen way too many mistakes by people who do not use the curly brackets and then, later on, add an additional command and forget to wrap it.

My attitude is to wrap it for readability and future extensibility.

PSR-2 Opening braces for control structures

My understanding of the reasoning here is basically to prevent blocks of contiguous code from becoming excessively long.

For example, say I have an 50 line function written in PSR-2 style. If that function contains 10 if() conditions and 5 loops, then my function under your rules would be 65 lines long.

Since it's a single function, I need to be able to work with it as a single entity, so it is really helpful to be able to see it all at once. With a 50-line function, that's feasible. It gets a lot harder if the function is 65 lines long.

In fact, looking at my editor window right now, I can see 30 lines at a time, so even a 50-line function is a bit too long to manage easily without resizing or removing the docked panels in my IDE.

Now I know that clean code rules would say that a 50-line function is far too long anyway and needs to be refactored. I'd agree with that. But guess what: functions with 50 lines or more are pretty common; I have to deal with them all time time, and the less unnecessary white space they have in them, the easier they are to work with.

Ultimately, however, this is just one interpretation of the root reasons behind it.

The real reason PSR-2 is this way is because that's how the consensus of opinion fell. They surveyed all the frameworks and others who had established PHP coding standards. All those different standards existed because people had sat down and thought about how best to format their code. They didn't agree because it is an opinionated subject, but there were broad areas of agreement and that was what went in to forming the PSR standards.

Can I use nested statements without curly brackets?

While to you this perhaps is compact and neat, it doesn't follow the convention on how these things are written. Your code will be hard to read by other developers. While there is no absolute "standard" on how to write code, there are several conventions that are adopted by a large percentage of the world.

One line if (something) do; statements are evil, break it into two lines even if you do not need to use curly braces:

if (something)
do;

This not only is easier to read but makes debugging easier as a break point can be placed on the "do" line if a debugger is being used, or if stepping the code it will be clear if the expression evaluated true or not.

In your case this would become:

if(!empty($consequences))
foreach($consequences as $consequence) {
// 100 lines of code to be inserted here
echo $consequence;
}
else
echo "No consequences";

While this is not "compact" as you would call it, it is maintainable, and very easy to see the code path which is your primary objective when writing clear code that is easy to debug later.

Also note that since PHP5.4 the array keyword is no longer required in PHP, you can use the following:

$consequences = ["You ", "will ", "burn ", "for ", "this!"];

Which is not only more "compact" but more standard inline with other languages such as C, and as such very readable.

In short, if you are not willing to adjust your viewpoint on what is "neat" code you are going to struggle in this industry. It will be hard for others to work with you, and it will be hard for you to read code written by others.

PHP anonymous curly braces?

PHP does not support variable scoping using braces (or any other syntax elements). They are just doing nothing in your example.

PHP CLI - comma-separated key/value pairs wrapped in curly braces - what are they?

Per section 3.5.1 of the Bash manual:

Brace expansion is a mechanism by which arbitrary strings may be generated. This mechanism is similar to filename expansion, but the filenames generated need not exist. Patterns to be brace expanded take the form of an optional preamble, followed by either a series of comma-separated strings or a sequence expression between a pair of braces, followed by an optional postscript. The preamble is prefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left to right.

In your case, there is no preamble or postscript, so it's just expanding to each of the elements in the list.

You can see the result by using echo:

echo {a=1,b=2,c=3}

Which outputs:

a=1 b=2 c=3

If you were to use a preamble and postscript:

echo before{a=1,b=2,c=3}after

You get:

beforea=1after beforeb=2after beforec=3after

I typically use this when trying to copy or move a file to a backup:

cp somefile.txt{,.bak}

Which expands to:

cp somefile.txt somefile.txt.bak


Related Topics



Leave a reply



Submit