我们如何在 php 中操作 std 类?

发布于 2024-10-09 04:32:42 字数 202 浏览 0 评论 0原文

是否可以像数组一样向 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

谷夏 2024-10-16 04:32:42

当然,您可以添加新元素...

$Object = new StdClass();
$Object->item1 = 1;
$Object->item2 = 2;

如果您想将对象作为数组进行迭代,您应该使用 PHP SPL ArrayIteratorRecursiveArrayIterator

您还可以使用类型转换从数组移动到对象并返回...

$array = array('item1', 'item2');
$Object = (object)$array;
var_dump($object);
$array = (array)$Object;
var_dump($array);

Sure, you can add new elements...

$Object = new StdClass();
$Object->item1 = 1;
$Object->item2 = 2;

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...

$array = array('item1', 'item2');
$Object = (object)$array;
var_dump($object);
$array = (array)$Object;
var_dump($array);
冷︶言冷语的世界 2024-10-16 04:32:42

是的,但没有数字索引。

  $a = new stdclass();
  $a->foo = 'item 1';
  $a->bar = 'item 2';
  $a->goobar = array('item1', 'item2');
  var_dump($a);

如果您想要更复杂的场景,请查看 ArrayAccessArrayObject.

Yes, but not numerically indexed.

  $a = new stdclass();
  $a->foo = 'item 1';
  $a->bar = 'item 2';
  $a->goobar = array('item1', 'item2');
  var_dump($a);

If you want more complex scenarios, look at ArrayAccess and ArrayObject.

俏︾媚 2024-10-16 04:32:42

好吧,文档指出:

通过类型转换为对象创建。

因此,您可以在 (array) 和 (object) 之间来回转换,以使用数组函数来使用 stdClass 实例。

Well, the documentation states:

Created by typecasting to object.

As such, you can cast back and forth between (array) and (object) to work stdClass instances with array functions.

青衫负雪 2024-10-16 04:32:42

操纵起来并不困难。我想说的是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文