PHP 中的简单对象问题 [新手]
我知道您可以创建一个像这样的数组:
$a = array();
并向其附加新的名称值对,如下所示:
$a['test'] = 'my new value';
甚至可以省略第一行,尽管这是不好的做法!
我发现对象更容易阅读和理解,所以我所做的就是获取名称值对的数组并将其转换为一个对象:
$a = (object)$a;
因此我可以访问参数:
$a->test;
创建数组的额外开销似乎很浪费是否可以简单地创建一个对象,然后以某种方式将名称值对添加到其中,就像我对数组所做的那样?
谢谢
I know you can create an array like this:
$a = array();
and append new name value pairs to it like thus:
$a['test'] = 'my new value';
It is even possible to omit the first line, although bad practice!
I find objects easier to read and understand, so what I've done is taken the array of name value pairs and cast it into an object:
$a = (object)$a;
Thus I can access the parameters:
$a->test;
It seems wasteful for the extra overhead of creating an Array to start with, is it possible to simply create an object and then somehow just add the name value pairs to it in a similar way as I would do the array?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,
stdClass
类就是为此而设计的。您可以将其视为类似于以下 JavaScript 代码:
事实上,如果您有一些以 JSON 形式接收数据的 PHP 代码,则对数据运行
json_decode()
会生成stdClass具有包含的属性的
对象。Yes, the
stdClass
class is designed for just that.You can think of it as being akin to the following JavaScript code:
In fact, if you had some PHP code that received data as JSON, running
json_decode()
on the data results in astdClass
object with the included properties.您可以使用
stdClass
对象来实现:You can use the
stdClass
object for that:即使没有 stdclass,它也非常简单。你可以简单地做
It is very simple even without stdclass. You can simply do
您可以使用 stdClass 来实现此目的。
You can use stdClass for this.