php 大括号和字符串

发布于 2024-09-27 07:16:44 字数 138 浏览 1 评论 0原文

谁能向我解释如何在 php 字符串中使用大括号 { } ?就像

“这是一个{$variable}”
“这是一个 {$user -> getName($variable);} 名称”

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"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

肤浅与狂妄 2024-10-04 07:16:44

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

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

来源

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

多像笑话 2024-10-04 07:16:44

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

$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

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
日裸衫吸 2024-10-04 07:16:44

此外,语法“this is a {$user -> getName($variable);} name”无效。您不能在字符串内调用函数/方法。但是你可以这样做:

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

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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文