Skip to content
Advertisement

Creating an array of objects in PHP

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:

$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();
    }
}

Advertisement

Answer

Any of the following are valid:

$myArray = array();
$myArray[] = new Object();
$myArray[1] = new Object();
array_push($myArray, new Object);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement