Is it possible to declare an array of objects? [closed]
Asked Answered
A

8

88

So I have been searching for a while and cannot find the answer to a simple question. Is it possible to have an array of objects in PHP? Such as:

$ar=array();    
$ar[]=$Obj1    
$ar[]=$obj2

For some reason I have not been able to find the answer anywhere. I assume it is possible but I just need to make sure.

Analysis answered 23/12, 2011 at 4:17 Comment(1)
Why not try it out and see what happens? Do you have any specific question about this?Jijib
S
138

The best place to find answers to general (and somewhat easy questions) such as this is to read up on PHP docs. Specifically in your case you can read more on objects. You can store stdObject and instantiated objects within an array. In fact, there is a process known as 'hydration' which populates the member variables of an object with values from a database row, then the object is stored in an array (possibly with other objects) and returned to the calling code for access.

-- Edit --

class Car
{
    public $color;
    public $type;
}

$myCar = new Car();
$myCar->color = 'red';
$myCar->type = 'sedan';

$yourCar = new Car();
$yourCar->color = 'blue';
$yourCar->type = 'suv';

$cars = array($myCar, $yourCar);

foreach ($cars as $car) {
    echo 'This car is a ' . $car->color . ' ' . $car->type . "\n";
}
Spoony answered 23/12, 2011 at 4:35 Comment(5)
I've tried the php site and haven't been able to find anything. I am also sitting with the book "PHP Objects, Patters, and Practice" by Matt Zandstra. and haven't been able to find any information.Analysis
Question: Suppose that you wanted to just print the color of just one Car in that array. Would you say echo $cars[0]->color; to print the first one, and echo $cars[1]->color; to print the second one?Thanatos
I just remembered that there is this great thing called Ideone, which lets you test out code snippets online. To answer my own question: yes, you can: ideone.com/8XB4TCThanatos
@MikeWarren: Correct, therein lies the power of hydrating an array of objects, aka as a 'collection'. You could also be specific about the keys each object gets, in case you need to retrieve specific objects within a collection, for example `$car['blue_4_door'] = $anotherCar'.Spoony
So if I have a 20 objects, I have to type 20 times $yourCar = new Car(); ? There is not some more elegant way to do that as in JS like let car = [{}, {},{}] ?Trifolium
B
31

Yes.

$array[] = new stdClass;
$array[] = new stdClass;

print_r($array);

Results in:

Array
(
    [0] => stdClass Object
        (
        )

    [1] => stdClass Object
        (
        )

)
Breakthrough answered 23/12, 2011 at 4:21 Comment(5)
I timed it and this took twenty seconds to test, including typing time.Breakthrough
So would my class name replace stdClass? What if the object is already created and you wanted to just add it to the array. Can use constructors with the method above? p.s. sorry I am new to SOAnalysis
There's nothing special about it. Add it to the array however you like. This is simply a demonstration that you can very, very easily test these kinds of things out yourself.Breakthrough
This is the answer to the question, while the accepted answer points towards an entirely different direction of OOPSCaenogenesis
@Breakthrough Yes, but it takes less than 5 seconds to Google this answer ;)Anglice
P
18

You can do something like this:

$posts = array(
  (object) [
    'title' => 'title 1',
    'color' => 'green'
  ],
  (object) [
    'title' => 'title 2',
    'color' => 'yellow'
   ],
   (object) [
     'title' => 'title 3',
     'color' => 'red'
   ]
);

Result:

var_dump($posts);

array(3) {
  [0]=>
  object(stdClass)#1 (2) {
    ["title"]=>
    string(7) "title 1"
    ["color"]=>
    string(5) "green"
  }
  [1]=>
  object(stdClass)#2 (2) {
    ["title"]=>
    string(7) "title 2"
    ["color"]=>
    string(6) "yellow"
  }
  [2]=>
  object(stdClass)#3 (2) {
    ["title"]=>
    string(7) "title 3"
    ["color"]=>
    string(3) "red"
  }
}
Pugh answered 16/8, 2021 at 22:53 Comment(0)
V
11

Yes, its possible to have array of objects in PHP.

class MyObject {
  private $property;

  public function  __construct($property) {
    $this->Property = $property;
  }
}
$ListOfObjects[] = new myObject(1); 
$ListOfObjects[] = new myObject(2); 
$ListOfObjects[] = new myObject(3); 
$ListOfObjects[] = new myObject(4); 

print "<pre>";
print_r($ListOfObjects);
print "</pre>";
Vestal answered 26/12, 2012 at 3:21 Comment(2)
Do we have to go on incrementing the constructor index in myObject() each time we want to add a new object in the array or is it optional? All this OOP stuff in web languages is simply OOPS!Heteropterous
@YoustayIgo that's just for the example, so that the output distinguishes the objects from each other. You can put whatever value you like in the constructor, it then simply assigns that value to the object's $property property.Jesicajeske
B
7

Arrays can hold pointers so when I want an array of objects I do that.

$a = array();
$o = new Whatever_Class();
$a[] = &$o;
print_r($a);

This will show that the object is referenced and accessible through the array.

Bisulcate answered 4/12, 2012 at 21:57 Comment(0)
B
5

Another intuitive solution could be:

class Post
{
    public $title;
    public $date;
}

$posts = array();

$posts[0] = new Post();
$posts[0]->title = 'post sample 1';
$posts[0]->date = '1/1/2021';

$posts[1] = new Post();
$posts[1]->title = 'post sample 2';
$posts[1]->date = '2/2/2021';

foreach ($posts as $post) {
  echo 'Post Title:' . $post->title . ' Post Date:' . $post->date . "\n";
}
Bose answered 25/2, 2021 at 16:3 Comment(1)
THE BEST ... saved me a lot of time. A small tweak here though, instead of doing this increment just try to put it inside a loop and use a variable for increment. doesn't matter if it's for a single or hundreds of objects and it will look more generic solution.Hunley
D
1

First of all create 2d array

$posts = array(
  [
    'title' => 'title 1',
  ],
  [
    'title' => 'title 2',
  ],
  [
     'title' => 'title 3',
  ]
);

$result = json_decode(json_encode($posts));

The result will return an array of objects.

Deedradeeds answered 22/5 at 6:5 Comment(0)
U
-1

Although all the answers given are correct, in fact they do not completely answer the question which was about using the [] construct and more generally filling the array with objects.

A more relevant answer can be found in how to build arrays of objects in PHP without specifying an index number? which clearly shows how to solve the problem.

Ubangishari answered 6/12, 2019 at 19:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.