Skip to content
Advertisement

Array of PHP Objects

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.

Advertisement

Answer

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";
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement