我们如何在 php 中操作 std 类?
是否可以像数组一样向 stdclass 添加元素?
Array (
[0] => item 1
[1] => item 2
)
Stdclass (
[0] => item 1
[1] => item 2
)
与数组相比,操作对象通常更困难吗?因为我们有很多数组函数可以使用等等。
Is it possible to add elements to stdclasses like we do for arrays?
Array (
[0] => item 1
[1] => item 2
)
Stdclass (
[0] => item 1
[1] => item 2
)
Is it generally harder to manipulate objects as compared to arrays? Since we have lots of array functions to make use of etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当然,您可以添加新元素...
如果您想将对象作为数组进行迭代,您应该使用 PHP SPL ArrayIterator 或 RecursiveArrayIterator。
您还可以使用类型转换从数组移动到对象并返回...
Sure, you can add new elements...
If you want to iterate object as array you should use PHP SPL ArrayIterator or RecursiveArrayIterator.
Also you can use typecasting to move from array to object and back...
是的,但没有数字索引。
如果您想要更复杂的场景,请查看 ArrayAccess 和 ArrayObject.
Yes, but not numerically indexed.
If you want more complex scenarios, look at ArrayAccess and ArrayObject.
好吧,文档指出:
因此,您可以在 (array) 和 (object) 之间来回转换,以使用数组函数来使用 stdClass 实例。
Well, the documentation states:
As such, you can cast back and forth between (array) and (object) to work stdClass instances with array functions.
操纵起来并不困难。我想说的是 count 和 array_search 之类的东西不适用于对象。
数组和对象都有其优点,这取决于您想要实现的目标。
http://php.net 文档将说明哪些数据类型可以传递给哪些函数。
It's no harder to manipulate. All I would say is things like count and array_search don't work on an object.
Array and objects both have their benefits it depends on what you are trying to achieve.
http://php.net documentation will state what data types can be passed to what functions.