convert an array to object using PHP
Web Development

Cast or Convert an Array to Object Using PHP (Hydrator Pattern)

In this post, we will convert an array to object using PHP hydrator pattern. This method is so simple, it’s about transferring data from one place to another.

We will define a class that will take an array and an object as inputs and search for all set() methods in the object and fills it with values from the array.

First, we will determine the object class using get_class() function then we will use get_class_methods() to get the class methods.

Keep in mind that we use PHP 7 coalescing operator (??), in case you are not using PHP 7, you can use ternary operator instead.

We use substr then we concatenate because if we have lowerCamelCase member variables like $firstName.

To test this converter class, we need to create a class with properties and methods (getters & setters) and see how to convert an array to object using PHP in action.

Let’s assume that we have an employee class like this:

Convert Array To Object

Now let’s create an array that will hold the data that will be transferred to the class.

Great, let’s convert the array data to the class.

Look at the result:

convert an array to object using php


You can convert an array to object using PHP hydrator pattern.

Convert Object to Associative Array

What about converting the object to an associative array, it’s the same concept, we are going to create a new function that does the opposite.

Our function will search for all get() functions the same way as the previous function like this:

Add this function to our converter class and call it with a passed object like this:


Note that the passed $obj here is the generated object from the array to object conversion process.

convert object to array using php

The output shows the associative array as expected.

I hope you find the post useful. Keep coming back.

Thank you.