Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it wrong to use curly braces after the dollar sign inside strings

Tags:

php

I am trying to understand what is the difference between the two possible syntax variations in complex variable syntax. PHP allows for both variants:

$foo = 'bar';
$bar = "${foo}bar is allowed"; //or
$bar = "{$foo}bar is allowed";

There is no error/warning/notice generated when using either syntax. I have noticed no difference between the two, however PHP manual shows only the {$foo} variant.
Is it wrong to use the other variant? Would it ever cause me any problems?

like image 318
Dharman Avatar asked Feb 24 '19 23:02

Dharman


People also ask

What do curly brackets symbolize?

Noun. Either of the two characters { and } , i.e., left curly bracket { and right curly bracket }, with the shape of a curved, pointed line, having various uses in math, music, computer programming and chemistry.

What curly braces problems?

This means that work needs to be invested in customization for each new installation, be it the adaptation of interfaces in the medical information system, the Arden Syntax server, or the code in the MLM itself. This problem is often referred to as the 'curly braces problem' in the Arden Syntax community.

What does the dollar sign and curly brackets mean in Javascript?

They allow for both multiline strings and string interpolation. Multiline strings: console. log(`foo bar`); // foo // bar.

How do you put curly braces on an F string?

If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.


1 Answers

${...} is a syntax for another purpose. It is used to indirectly reference variable names. Without string interpolation, literal names in curly braces or brackets are written as string literals, thus enclosed in quotes. However, inside interpolation quotes are not used outside curly braces:

$bar = 'baz';

echo $bar , PHP_EOL;
echo ${'bar'} , PHP_EOL;

$arr = ['a' => 1, 'b' => ['x' => 'The X marks the point.']];
echo $arr['a'] , PHP_EOL;

// interpolation:
echo "$arr[a] / {$arr['a']}" , PHP_EOL;

Instead of literals you can use functions as well:

function foo(){return "bar";}

// Here we use the function return value as variable name.
// We need braces since without them the variable `$foo` would be expected
// to contain a callable

echo ${foo()} , PHP_EOL;

When interpolating, you need to enclose into curly braces only when the expression otherwise would be ambiguous:

echo "$arr[b][x]", PHP_EOL;       // "Array[x]"     
echo "{$arr['b']['x']}", PHP_EOL; // "The X marks the point."

Now we understand that ${...} is a simple interpolation "without braces" similar to "$arr[a]" since the curly braces are just for indirect varable name referencing. We can enclose this into curly braces nevertheless.

Interpolated function call forming the variable name:

echo "${foo()} / {${foo()}}", PHP_EOL;
// "baz / baz" since foo() returns 'bar' and $bar contains 'baz'.

Again, "${bar}" is equivalent to ${'bar'}, in curly braces: "{${'bar'}}".


As asked in comments,

there is another curly brace syntax to reference array keys.

$someIdentifier{'key'}

This is just an alternative syntax to PHP's common array syntax $array['key'].

In opposit to the latter, on indirect variable name references the curly braces follow immediately after the $ or the object member operator ->. To make it even more cryptic we can combine both:

$bar['baz'] = 'array item';
echo ${'ba' . 'r'}{'ba'.'z'};

which is equivalent to echo $bar['baz'];

Really weird in PHP's string interpolation: "${bar}" is valid and "${'bar'}" as well but not "$array['key']", "$array[key]" is valid instead, but both, "$array{key}" and "$array{'key'}", do not work at all.

Conclusion

It should be made a habit to use braced interpolation syntax all the time. Braced array key syntax should be avoided at all.
Always use:

"{$varname} {$array['key']} {${funcname().'_array'}['key']}"

See also PHP documentation:

  • Complex curly syntax

(to distinguish from)

  • Variable variables (also known as indirect variable name referencing)

  • Accessing array elements

    Both square brackets and curly braces can be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} will both do the same thing in the example above).

like image 169
Quasimodo's clone Avatar answered Sep 29 '22 20:09

Quasimodo's clone