{$var} 和 $var 有什么区别?
我想知道何时以及为什么应该使用 {$var}
echo "This is a test using {$var}";
以及何时(以及为什么)应该使用简单形式 $var
echo "This is a test using $var";
I would like to know when and why should I use {$var}
echo "This is a test using {$var}";
and when (and why) should I use the simple form $var
echo "This is a test using $var";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当 a) 不访问对象或数组来获取值,并且 b) 变量名称后面没有可能被解释为变量名称一部分的字符时,您可以使用后者。
You would use the latter when a) not accessing an object or array for the value, and b) no characters follow the variable name that could possibly be interpreted as part of it.
http://php.net/manual/en/language.variables.variable.php
http://php.net/manual/en/language.variables.variable.php
在某些特殊情况下,括号允许您消除 PHP 解析器的歧义。
就您而言,它们是等效的。
但请考虑这一点:
如果没有括号,您将无法获得预期的结果:
为了清楚起见,我强烈建议不要使用这种语法。
The brackets allow you to remove ambiguity for the PHP parser in some special cases.
In your case, they are equivalent.
But consider this one:
Without the brackets, you will not get the expected result:
For clarity purposes, I would however strongly advise against this syntax.
如果您编写
echo "This is a test using $vars"
您不会在结果文本中获得 $var 的内容。
如果你写
echo "This is a test using {$var}s";
一切都会好起来的。
PS 它仅适用于“”,但不适用于“”。
If you write
echo "This is a test using $vars"
You do not get content of $var in result text.
If you write
echo "This is a test using {$var}s";
Everything will be OK.
P.S. It works only with "" but not for ''.
{}
表示法对于在字符串中嵌入多维数组也很有用。例如
将被解析为
并且您最终会得到文本
但是如果您这样做,
您最终会得到预期的结果
The
{}
notation is also useful for embedding multi-dimensional arrays in strings.e.g.
will be parsed as
and you'll end up with the text
But if you do
you end up with the expected