Whats the {} tag do in php?

Possible Duplicate:
curly braces in string

Just came across this piece of code and it got me curious...

$msg .= "–{$mime_boundary}–n";   

The $mime_boundary var was specified earlier to be output as a string.

Did a quick test....

$var = "XmytextX";
$str ="some wrapper{$var}end of";
echo $str; 

and it does indeed output into the string. I've just never seen this way of outputting a var before.

Couldn't find any documentation on it - can anyone enlighten me?


So, normally, you could use the double quotes to output any variable like so:

echo "Hello, $name";

But, what if you wanted to output an item inside an array?

echo "Hello, $row['name']";

That wouldn't work. So, you would enclose the variable in curly brackets to tell the compiler to interpolate the entire variable:

echo "Hello, {$row['name']}";

On that note, you could also use it with objects:

echo "Hello, {$row->name}";

Hope that helps!


It's called variable-interpolation. In fact you don't need the {} around the var at all. This would also work:

echo "The value of my var is $var";

However if you need a more complex variable to output it sometimes only works with the {} . For example:

echo "This is a {$very['long']['and']['complex']['variable']}";

Also note, that variable-interpolation only works in strings with double-quotes! So this wouldn't work:

echo 'this is my $var';
// outputs: this is my $var

The curly braces set a variable name off from the rest of the text, allowing you to avoid the use of spaces.

For example, if you removed the curly braces, the PHP engine would not recognize $mime_boundary as a variable in the following statement:

$msg .= "–$mime_boundary–n";

By encapsulating the variable in curly braces, you tell the PHP engine to process the variable and return its value.

链接地址: http://www.djcxy.com/p/59528.html

上一篇: PHP连接使用{}

下一篇: 什么是{}标签在PHP中做什么?