Whats the {} tag do in php? [duplicate]
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.
It's there to eliminate ambiguity: in your case, if you wrote "some wrapper $vared of"
, it's clear that PHP will try to put there the value of $vared
, and that's not what you want.
The curly braces let you specify which part of the string should be interpolated.
Consider $str ="some wrapper{$var}end of";
verses $str ="some wrapper$varend of";
They also allow you to insert array elements and class variables directly into strings
$str = "foobar $foo['bar']"; // parse error
$str = "foobar {$foo['bar']}";
$str = "this is my {$foo->bar[1]}";
It's related to variable interpolation.
This is explained in the manual (under "Complex (curly) syntax"). I'm curious as to why you haven't read it if you are working in PHP.
If you take a look at http://php.net/manual/en/language.types.string.php you'll see its just another way of embedding a variable within a string, it just allows you to define where the end of the variable is.
For example:
$var = "Animal"
echo "The {$var}s"; //Outputs "The Animals"
精彩评论