How to handle an array of PHP objects.

This is a short guide on how to work with a PHP array that contains objects. In this example, we will create multiple objects and then add them to a PHP array. Afterwards, we will loop through that array of objects and call one of their methods.

For the purposes of this post, I have created an example PHP class called Person:

class Person{

    //Person's name.
    public $name;

    //Object constructor allows us to set the Person's name.
    public function __construct($name){
        $this->name = $name;
    }

    //Object method that prints out "Hi!"
    public function sayHi(){
        echo 'Hi, I\'m ' . $this->name;
    }
}

This PHP class above is pretty simple. It has an attribute called $name, which will contain the name of the Person and it has a function called “sayHi”, which prints out the object’s name to the browser.

Adding PHP objects to an array.

Now, let’s create a few objects from this class and then add them to an array:

//Empty array.
$people = array();

//Create three Person objects. Each with a different name.
//Add each Person object to our $people array.
$person1 = new Person('Dave');
$people[] = $person1;

$person2 = new Person('Sarah');
$people[] = $person2;

$person3 = new Person('Michael');
$people[] = $person3;

In the PHP snippet above, we created three Person objects called Dave, Sarah and Michael. We then added each object to an array called $people.

Looping through an array of objects.

Now, let’s loop through that array and call the “sayHi” method on each object:

//Loop through our array of objects
//and call the sayHi method.
foreach($people as $person){
    $person->sayHi();
}

If you run the PHP code above, you will see that we were able to loop through our objects and access them as we normally would. In this case, they each printed out their own individual name.

It’s that simple.

Hopefully, this post helped a little!