I'm working on this PHP code collaboration and it seems that some people access PHP StdClass fields like this
我正在研究这个PHP代码协作,似乎有些人会像这样访问PHP StdClass字段
$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?
据我所知,这些是等价的。是吗?使用哪个是否重要?你更喜欢哪种方式?有什么怪癖要注意吗?
2 个解决方案
#1
21
They are equivalent. You only need the second version if you want to use abhorrent attribute names like:
它们是等价的。如果您想使用可恶的属性名称,则只需要第二个版本:
$data->{'what * the ! thing'}
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):
但是还有双引号版本,当你真正需要变量属性名称(基本上是对象的变量变量)时会更有意义:
$data->{"attr$index"}
#2
2
I need to create class with abnormal property names like this {'field-name'}.
我需要创建具有异常属性名称的类,例如this {'field-name'}。
class myclass
{
public {'field-name-with-minus-sign'} = "something";
}
Id doesnt work. Why? I dont want to use something like this:
我不工作。为什么?我不想使用这样的东西:
$myclass = new stdClass();
$myclass->{'dumb-property-name'}
because i have a lot of properties like this.
因为我有很多像这样的属性。
#1
21
They are equivalent. You only need the second version if you want to use abhorrent attribute names like:
它们是等价的。如果您想使用可恶的属性名称,则只需要第二个版本:
$data->{'what * the ! thing'}
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):
但是还有双引号版本,当你真正需要变量属性名称(基本上是对象的变量变量)时会更有意义:
$data->{"attr$index"}
#2
2
I need to create class with abnormal property names like this {'field-name'}.
我需要创建具有异常属性名称的类,例如this {'field-name'}。
class myclass
{
public {'field-name-with-minus-sign'} = "something";
}
Id doesnt work. Why? I dont want to use something like this:
我不工作。为什么?我不想使用这样的东西:
$myclass = new stdClass();
$myclass->{'dumb-property-name'}
because i have a lot of properties like this.
因为我有很多像这样的属性。