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

Full Article :

LikeGeeks - https://likegeeks.com/convert-array-to-object-using-php/

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.

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’,

Leave a Comment

%d bloggers like this: