tags:

views:

75

answers:

2

can anyone let me know the meaning of { } [curly braces] in outputting a string ?

+2  A: 

They're used to escape variable expressions. From Strings:

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

In fact, any value in the namespace can be included in a string with this syntax. Simply write the expression the same way as it would appear outside the string , and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."; 

// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"; 

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
?>

I say "escape" because you can do this:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

or

$out = "{$a} {$a}"; // same

so in this case the curly braces are unnecessary but:

$out = "$aefgh";

will, depending on your error level, either not work or produce an error because there's no variable named $aefgh so you need to do:

$out = "${a}efgh"; // or
$out = "{$a}efgh";
cletus
huh? no, they are not
stereofrog
even if you copypaste the whole php manual here, this still isn't "escaping". The proper term is "interpolation", or "parsing" (although the latter is quite confusing), and "escaping" is something completely different.
stereofrog
I think copy-pasting is bad idea. Manual constantly changing, but copypasted content would remain the same. But it's good to get reputation, of course :)
Col. Shrapnel
+1  A: 

You're probably referring to variable interpolation

stereofrog