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

In this post, we will convert an array to an object using the 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 the get_class() function then we will use get_class_methods() to get the class methods.

class Converter
{
 public static function toObject(array $array, $object)
        {
            $class = get_class($object);
            $methods = get_class_methods($class);
            foreach ($methods as $method) {
                preg_match(' /^(set)(.*?)$/i', $method, $results);
                $pre = $results[1]  ?? '';
                $k = $results[2]  ?? '';
                $k = strtolower(substr($k, 0, 1)) . substr($k, 1);
                If ($pre == 'set' && !empty($array[$k])) {
                    $object->$method($array[$k]);
                }
            }
            return $object;
        }
}

Keep in mind that we use PHP 7 coalescing operator (??), in case you are not using PHP 7, you can use the 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:

class Employee
{
    protected $name;
    protected $phone;
    protected $email;
    protected $address;
    public function getName()
    {
        return $this->name;
    }
    public function getPhone()
    {
        return $this->phone;
    }
    public function getEmail()
    {
        return $this->email;
    }
    public function getAddress()
    {
        return $this->address;
    }
    public function setName($name)
    {
        $this->name = $name;
    }
    public function setPhone($phone)
    {
        $this->phone = $phone;
    }
    public function setEmail($email)
    {
        $this->email = $email;
    }
    public function setAddress($address)
    {
        $this->address = $address;
    }
}

Convert array to object

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

$arr['name'] = "Adam";
$arr['phone'] = "123456";
$arr['email'] = "adam@mail.com";
$arr['address'] = "U.S";

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

$obj = Converter::toObject($arr, new Employee());
var_dump($obj);

Look at the result:

convert an array to object using php

Cool!!

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

Convert an object to an 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:

public static function toArray($object)
{
    $array = array();
    $class = get_class($object);
    $methods = get_class_methods($class);
    foreach ($methods as $method) {
        preg_match(' /^(get)(.*?)$/i', $method, $results);
        $pre = $results[1]  ?? '';
        $k = $results[2]  ?? '';
        $k = strtolower(substr($k, 0, 1)) . substr($k, 1);
        If ($pre == 'get') {
            $array[$k] = $object->$method();
        }
    }
    return $array;
}

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

var_dump(Converter::toArray($obj));

Note that the passed $obj here is the generated object from the array to the 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.

7 thoughts on “Cast or Convert an Array to Object Using PHP (Hydrator Pattern)
    1. The results variable is an empty variable which is filled with the results of the regex search, where $results[0] contains the text that matches the full pattern and $results[1] is the first captured subpattern.
      Hope that helps.

  1. in what situation is this mechanism used? I liked it but I do not know when to use it. Thank you

    1. It’s about transferring data from one object to another using a design pattern called hydrator pattern.
      Like most modern PHP frameworks do, they use design patterns to work with data and give the user a good abstraction without digging deep into the details.

Leave a Reply

Your email address will not be published. Required fields are marked *