在 PHP 中创建对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8451226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:45:06  来源:igfitidea点击:

Creating an array of objects in PHP

phpoopobject

提问by Povylas

I would like to know what is the right of creating objects arrays in php.
My goal here is to be able to get data like this:

我想知道在 php 中创建对象数组的权利是什么。
我的目标是能够获得这样的数据:

$obj = new MyClass();
echo $obj[0]->parameter; //value1
echo $obj[1]->parameter; //value2

Thanks for your time.

谢谢你的时间。

EDIT: And if I want to do it in class it should look like this?

编辑:如果我想在课堂上做它应该是这样的?

class MyClass{
    public $property;

    public function __construct() {
        $this->property[] = new ProjectsList();
    }
}

回答by Byron Whitlock

Any of the following are valid:

以下任何一项都是有效的:

$myArray = array();
$myArray[] = new Object();
$myArray[1] = new Object();
array_push($myArray, new Object);

回答by Jim Jose

Try this,

尝试这个,

$obj = array(new stdClass(), new stdClass())

or

或者

$obj = array()
$obj[] = new stdClass()
$obj[] = new stdClass()

EDIT: Classto stdClass

编辑: ClassstdClass

回答by Chillie

Honestly, I think you are on the right path. from what it sounds like you are not just trying to add to arrays, but convert arrays to objects.

老实说,我认为你走在正确的道路上。从听起来你不仅仅是想添加到数组,而是将数组转换为对象。

<?php
 $obj = (object) 'ciao';
 echo $obj->scalar;  // outputs 'ciao'
 ?>

PHP Objects

PHP 对象

EDIT: I don't think you could add an object like this:

编辑:我认为您不能添加这样的对象:

  $this->property[] = new ProjectsList();

the "new ProjectsList()" would be how you would create an object from a class. ProjectsList would need to be a class. it would look more like this:

“new ProjectsList()”将是您从类创建对象的方式。ProjectsList 需要是一个类。它看起来更像这样:

   $obj = new ProjectsList;
   $this->property[] = $obj;

you would need to make sure the ProjectsList existed first though.

不过,您首先需要确保 ProjectsList 存在。