如何访问以数字开头的对象属性?

编程入门 行业动态 更新时间:2024-10-25 08:27:28
本文介绍了如何访问以数字开头的对象属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用现有的代码库,并返回了一个对象,该对象的属性以数字开头,可以看到是否在该对象上调用了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

这是另一个提供有关解析方式的其他信息: PHP语法注释

And here's another one that gives some additionnal informations about the way those are parsed : PHP grammar notes

更多推荐

如何访问以数字开头的对象属性?

本文发布于:2023-11-06 05:24:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562815.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:开头   属性   对象   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!