views:

77

answers:

3

can anyone explain to me how to use the curly braces { } in php strings? like

"this is a {$variable}"
"this is a {$user -> getName($variable);} name"

+8  A: 

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works; "'" is an invalid character for variable names
echo "He drank some $beers";   // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>

Source

Gazler
I always use curly braces when putting variables in strings like this. Even if it's not needed
Joe Philllips
+2  A: 

It's used to specify the end of the variable name, for example:

$var = "apple";

echo "I love $var!"; //I love apple!
echo "I love $vars!"; // I love !
echo "I love {$var}s!"; //I love apples!
echo "I love ${var}s!"; //I love apples! //same as above
Ruel
"I love $vars!" will return an "Undefined variable" notice though.
Alec
+1  A: 

Also the syntax "this is a {$user -> getName($variable);} name" isn't valid. You can't call functions/methods inside of strings. You could however do this:

"this is a " . $user->getName($varaible) . " name"
mellowsoon