php大括号和字符串

时间:2010-10-12 16:18:41

标签: php string variables brackets

任何人都可以向我解释如何在php字符串中使用花括号{}吗?像

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

3 个答案:

答案 0 :(得分:8)

如果遇到美元符号($),解析器将贪婪地获取尽可能多的令牌以形成有效的变量名称。将变量名称括在花括号中以显式指定名称的结尾。

<?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

答案 1 :(得分:3)

它用于指定变量名称的结尾,例如:

$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

答案 2 :(得分:1)

语法“这是{$ user - &gt; getName($ variable);} name”也无效。你不能在字符串中调用函数/方法。但是你可以这样做:

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