PHP StdClass - 访问字段为 ->field 或 ->{'field'}
我正在研究这个 PHP 代码协作,似乎有些人像这样访问 PHP StdClass 字段
$body->head
,而其他人则
$body->{'head'}
像据我所知,这些字段是等效的。他们是吗?使用哪个有关系吗?您更喜欢哪种方式?这里有什么需要注意的怪癖吗?
I'm working on this PHP code collaboration and it seems that some people access PHP StdClass fields like this
$body->head
and others like
$body->{'head'}
As far as I can tell these are equivalent. Are they? Does it matter which is used? Which way would you prefer? Any quirks to look out for here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它们是等价的。如果您想使用令人厌恶的属性名称,则只需要第二个版本,例如:
如果将纯数据数组转换为对象,有时会发生这种情况。
但还有双引号版本,当您实际需要变量属性名称(基本上是对象的变量变量)时,它更有意义:
They are equivalent. You only need the second version if you want to use abhorrent attribute names like:
This sometimes happens if you convert pure data arrays into objects.
But there is also the double quotes version, which makes a bit more sense when you actually need variable attribute names (basically variable variables for objects):
我需要创建具有异常属性名称的类,例如 {'field-name'}。
身份证不行啊为什么?我不想使用这样的东西:
因为我有很多这样的属性。
I need to create class with abnormal property names like this {'field-name'}.
Id doesnt work. Why? I dont want to use something like this:
because i have a lot of properties like this.