6

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)?

1
  • 1
    based on previous questions of yours, it looks like you have a braces {c}{o}{m}{p}{l}{e}{x} Commented Jul 10, 2012 at 22:03

3 Answers 3

9

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).

Sign up to request clarification or add additional context in comments.

2 Comments

I've seen that in many Coding Styles for consistency the form ${var} is deprecated and never permitted. Check the Zend Coding Style #Variable Substitution
@Fabio sounds good to me; I would avoid ${} altogether. I would also avoid {} except for the couple cases when it's necessary (multi-dimensional array access, method calls, object operator chaining).
4

The brackets delimit where the variable name ends; this example should speak for itself.

$a = "hi!"

echo "$afoo";  //$afoo is undefined

echo "${a}foo";  //hi!foo

echo "{$a}foo";  //hi!foo

Also, this should spit out a warning; you should use

${'a'}

Otherwise it will attempt to assume a is a constant.

1 Comment

echo "{$a}foo"; should produce the same as echo "${a}foo";, the curly braces will not echo to the screen.
1

Also you can use braces to get Char in the position $i of string $text:

$i=2;
$text="safi";

echo $text{$i}; // f

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.