在PHP中,我怎么能添加对象元素的数组? [英] In PHP, how can I add an object element to an array?
本文介绍了在PHP中,我怎么能添加对象元素的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用PHP。我有对象的数组,并想将一个对象添加到它的结束。
I'm using PHP. I have an array of objects, and would like to add an object to the end of it.
$myArray[] = null; //adds an element
$myArray[count($myArray) - 1]->name = "my name"; //modifies the element I just added
以上是功能性的,但有一个更清洁,编写更可读的方式?也许一条线?
The above is functional, but is there a cleaner and more-readable way to write that? Maybe one line?
推荐答案
只要做到:
$object = new stdClass();
$object->name = "My name";
$myArray[] = $object;
您需要先(即新
线)创建对象,然后将其推到数组的结束( []
线)。
You need to create the object first (the new
line) and then push it onto the end of the array (the []
line).
您也许可以做到这一点,以及:
You can probably do this as well:
$myArray[] = (object) array('name' => 'My name');
不过我认为这不是为可读,哪怕是更加简洁。
However I would argue that's not as readable, even if it is more succinct.
这篇关于在PHP中,我怎么能添加对象元素的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文