Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP parser: braces around variables

Tags:

php

I was wondering, how is the semantics of braces exactly defined inside PHP? For instance, suppose we have defined:

$a = "foo";

then what are the differences among:

echo "${a}";

echo "{$a}";

that is, are there any circumstances where the placement of the dollar sign outside the braces as opposed to within braces makes a difference or is the result always the same (with braces used to group just about anything)?

like image 635
John Goche Avatar asked Jul 10 '12 21:07

John Goche


1 Answers

There are a lot of possibilities for braces (such as omitting them), and things get even more complicated when dealing with objects or arrays.

I prefer interpolation to concatenation, and I prefer to omit braces when not necessary. Sometimes, they are.

You cannot use object operators with ${} syntax. You must use {$...} when calling methods, or chaining operators (if you have only one operator such as to get a member, the braces may be omitted).

The ${} syntax can be used for variable variables:

$y = 'x';
$x = 'hello';
echo "${$y}"; //hello

The $$ syntax does not interpolate in a string, making ${} necessary for interpolation. You can also use strings (${'y'}) and even concatenate within a ${} block. However, variable variables can probably be considered a bad thing.

For arrays, either will work ${foo['bar']} vs. {$foo['bar']}. I prefer just $foo[bar] (for interpolation only -- outside of a string bar will be treated as a constant in that context).

like image 76
Explosion Pills Avatar answered Sep 18 '22 00:09

Explosion Pills