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.
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.
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.
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.
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.
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"; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With