如何访问以数字开头的对象属性? [英] How can I access an object attribute that starts with a number?
问题描述
我正在使用现有的代码库,并返回了一个对象,该对象的属性以数字开头,可以看到是否在该对象上调用了print_r
.
I'm working on an existing code base and got back an object with an attribute that starts with a number, which I can see if I call print_r
on the object.
假设它是$Beeblebrox->2ndhead
.当我尝试像这样访问它时,出现错误:
Let's say it's $Beeblebrox->2ndhead
. When I try to access it like that, I get an error:
解析错误:语法错误,意外的T_LNUMBER,预期为T_STRING或T_VARIABLE或'{'或'$'
Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$'
如何获取该属性?
推荐答案
这是怎么回事:
$Beeblebrox->{'2ndhead'}
实际上,您几乎可以对任何种类的变量执行此操作,即使不是类属性的变量也是如此.
Actually, you can do this for pretty much any kind of variable -- even for ones that are not class properties.
例如,您可以考虑一个包含空格的变量名称;以下语法将起作用:
For example, you could think about a variable's name that contains spaces ; the following syntax will work :
${"My test var"} = 10;
echo ${"My test var"};
即使,显然,您将无法执行以下操作:
Even if, obviously, you would not be able to do anything like this :
$My test var = 10;
echo $My test var;
不过,不知道它在内部如何工作.经过一番搜索,我在PHP手册中找不到任何有关此的信息.
No idea how it's working internally, though... And after a bit of searching, I cannot find anything about this in the PHP manual.
Only thing I can find about {}
and variables is in here : Variable parsing -- but not quite related to the current subject...
但是这里的文章显示了其他两种可能性,并且比我在此处发布的示例更进一步: PHP变量名:Curly Brace Madness
But here's an article that shows a couple of other possiblities, and goes farther than the examples I posted here : PHP Variable Names: Curly Brace Madness
And here's another one that gives some additionnal informations about the way those are parsed : PHP grammar notes
这篇关于如何访问以数字开头的对象属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!