PHP parser: brackets around variables

I was wondering how exactly the semantics of curly braces are defined inside PHP? For example, suppose we define:

$a = "foo"; 

then what are the differences between them:

 echo "${a}"; echo "{$a}"; 

that is, are there any circumstances in which the placement of the dollar sign outside the curly braces, and not inside the curly braces, is the difference or the result is always the same (using braces to group anything)?

+6
source share
3 answers

There are many possibilities for curly braces (for example, deleting them), and everything becomes even more complicated when working with objects or arrays.

I prefer interpolation for concatenation, and I prefer to skip braces when not needed. Sometimes they are.

You cannot use object operators with the syntax ${} . You must use {$...} when calling methods or chain operators (if you have only one statement, for example, to get a member, curly braces can 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 in the ${} block. However, variable variables can probably be considered bad.

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

+8
source

In parentheses indicate 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 

In addition, this should throw a warning; you should use

 ${'a'} 

Otherwise, he will try to assume that a is a constant.

+4
source

You can also use curly braces to get Char at position $i string $text :

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

echo $text{$i}; // f

+1
source

Source: https://habr.com/ru/post/920167/


All Articles