PHP解析器:大括号围绕变量 [英] PHP parser: braces around variables
问题描述
我想知道大括号的语义是如何精确定义的 在PHP里面?例如,假设我们已定义:
I was wondering, how is the semantics of braces exactly defined inside PHP? For instance, suppose we have defined:
$a = "foo";
然后有什么区别:
echo "${a}";
echo "{$a}";
也就是说,在任何情况下 大括号外的美元符号与大括号内的美元符号相反 差异或结果始终相同(使用花括号) 几乎可以分组)?
that is, are there any circumstances where the placement of the dollar sign outside the braces as opposed to within braces makes a difference or is the result always the same (with braces used to group just about anything)?
推荐答案
花括号的可能性很多(例如省略它们),并且在处理对象或数组时事情变得更加复杂.
There are a lot of possibilities for braces (such as omitting them), and things get even more complicated when dealing with objects or arrays.
相对于串联,我更喜欢插值,并且在不需要时,我更喜欢省略花括号.有时候是.
I prefer interpolation to concatenation, and I prefer to omit braces when not necessary. Sometimes, they are.
您不能使用${}
语法使用对象运算符.调用方法或链接运算符时,必须使用{$...}
(如果只有一个运算符来获取成员,则可以省略花括号).
You cannot use object operators with ${}
syntax. You must use {$...}
when calling methods, or chaining operators (if you have only one operator such as to get a member, the braces may be omitted).
${}
语法可用于变量变量:
The ${}
syntax can be used for variable variables:
$y = 'x';
$x = 'hello';
echo "${$y}"; //hello
$$
语法不会在字符串中插值,因此需要${}
进行插值.您还可以使用字符串(${'y'}
),甚至可以在${}
块内连接.但是,可变变量可能被认为是一件坏事.
The $$
syntax does not interpolate in a string, making ${}
necessary for interpolation. You can also use strings (${'y'}
) and even concatenate within a ${}
block. However, variable variables can probably be considered a bad thing.
对于数组,任何一个都将在${foo['bar']}
与{$foo['bar']}
之间工作.我更喜欢$foo[bar]
(仅用于插值-在字符串bar
之外的字符串在该情况下将被视为常量).
For arrays, either will work ${foo['bar']}
vs. {$foo['bar']}
. I prefer just $foo[bar]
(for interpolation only -- outside of a string bar
will be treated as a constant in that context).
这篇关于PHP解析器:大括号围绕变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!