如何在不指定索引号的情况下用PHP构建对象数组? [英] how to build arrays of objects in PHP without specifying an index number?
问题描述
这是一个奇怪的问题.我正在手动构建对象数组,如下所示:
Here is a weird question. I am building an array of objects manually, like this:
$pages_array[0]->slug = "index";
$pages_array[0]->title = "Site Index";
$pages_array[0]->template = "interior";
$pages_array[1]->slug = "a";
$pages_array[1]->title = "100% Wide (Layout A)";
$pages_array[1]->template = "interior";
$pages_array[2]->slug = "homepage";
$pages_array[2]->title = "Homepage";
$pages_array[2]->template = "homepage";
我喜欢这是多么的清晰,但是由于我必须指定索引号,因此我无法轻松地重新排列它们.没有索引号怎么办?相关,有什么更好的方法?
I like how clearcut this is, but because I have to specify the index number, I can't rearrange them easily. How can I do this without the index number? Related, what is a better way to do this?
我还尝试通过创建一个类来编写此代码,并让数组上的每个点都成为该类的实例.但是,由于这是一个配置文件,因此很难读取和知道哪个参数与哪个参数一起使用.这就是为什么我在上面选择了这种过时的方法.
I also tried writing this by making a class, and having each spot on the array be instances of that class. But since this is a configuration file, it was hard to read and know what argument went with what parameter. That's why I chose this old-school method above.
任何想法都值得赞赏!
推荐答案
此代码
$pages_array[1]->slug = "a";
无论如何
都是无效的-如果未正确初始化对象,则会收到严格"警告.因此,您必须以某种方式构造对象-可以使用构造函数:
is invalid anyways - you'll get a "strict" warning if you don't initialize the object properly. So you have to construct an object somehow - either with a constructor:
$pages_array[] = new MyObject('index', 'title'....)
或使用stdclass强制转换
or using a stdclass cast
$pages_array[] = (object) array('slug' => 'xxx', 'title' => 'etc')
这篇关于如何在不指定索引号的情况下用PHP构建对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!