What is the difference between {$ var} and $ var?

I would like to know when and why I should use {$ var}

echo "This is a test using {$var}";

and when (and why) should use the simple form $ var

echo "This is a test using $var";
+3
source share
6 answers

You would use the latter when a) did not access the object or array for the value, and b) no characters follow the name of the variable, which can be interpreted as part of it.

+4
source

http://php.net/manual/en/language.variables.variable.php

, . , $$ a [1], , $a [1] , $$ a , [1] . : ${$ a [1]} ${$ a} [1] .

+4

PHP . .

:

$foobar = 'hello';
$foo = 'foo';
echo "${$foo . 'bar'}"; // hello

:

echo "$$foo . 'bar'"; // $foo . 'bar'

.

+3

echo "This is a test using $ vars"

You do not get content from $ var in the text of the result.

If you write

echo "This is a test using {$ var} s";

Everything will be OK.

PS It only works with "", but not for '.

+1
source

The notation is {}also useful for embedding multidimensional arrays in strings.

eg.

$array[1][2] = "square";

$text = "This $array[1][2] has two dimensions";

will be analyzed as

$text = "This " . $array[1] . "[2] has two dimensions";

and you will get the text

This Array[2] has two dimensions

But if you do

$text = "This {$array[1][2]} has two dimensions";

you will get the expected

This square has two dimensions.
+1
source

All Articles