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:

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:

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:

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!

Facebook Comments