Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of PHP Objects

Tags:

arrays

object

php

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.

like image 984
Beamer180 Avatar asked Dec 23 '11 04:12

Beamer180


People also ask

What is array of objects in PHP?

Let's explain what is an object and associative array in PHP? An object is an instance of a class meaning that from one class you can create many objects. It is simply a specimen of a class and has memory allocated. While on the other hand an array which consists of string as an index is called associative array.

Can you have an array of objects in PHP?

We can use the array() function to create an array of objects in PHP. The function will take the object as the arguments and will create an array of those objects. We can create objects by creating a class and defining some properties of the class. The properties of the class will have some values.

How do you call an array of objects in PHP?

To define an array you can use array() or for PHP >=5.4 [] and you assign/set an array/-element. While when you are accessing an array element with [] as mentioned above, you get the value of an array element opposed to setting an element.

Is PHP an object or array?

Definition and UsageThe is_array() function checks whether a variable is an array or not. This function returns true (1) if the variable is an array, otherwise it returns false/nothing.


1 Answers

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"; } 
like image 56
Mike Purcell Avatar answered Sep 29 '22 23:09

Mike Purcell