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"

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

I always use curly braces when putting variables in strings like this. Even if it's not needed
3

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

1 Comment

"I love $vars!" will return an "Undefined variable" notice though.
1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.