Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array of objects in PHP

Tags:

object

oop

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();
    }
}
like image 683
Povylas Avatar asked Dec 09 '11 20:12

Povylas


2 Answers

Any of the following are valid:

$myArray = array();
$myArray[] = new Object();
$myArray[1] = new Object();
array_push($myArray, new Object);
like image 176
Byron Whitlock Avatar answered Oct 22 '22 04:10

Byron Whitlock


Try this,

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

or

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

EDIT: Class to stdClass

like image 45
Jim Jose Avatar answered Oct 22 '22 04:10

Jim Jose