Advertisement
Guest User

PHP Array To Object

a guest
Jul 30th, 2012
397
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.85 KB | None | 0 0
  1. //original code: http://stackoverflow.com/questions/1869091/convert-array-to-object-php
  2.  
  3. static function arrayToObject($array, $class = 'stdClass', $strict = false) {
  4.         if (!is_array($array)) {
  5.             return $array;
  6.         }
  7.  
  8.         /* Fix-me: testar parametros do metodo construtor
  9.          * $optional = false;
  10.         //$object = new $class();
  11.         $r = new ReflectionMethod($class, '__construct');
  12.         $params = $r->getParameters();
  13.         foreach ($params as $param) {
  14.             //$param is an instance of ReflectionParameter
  15.             if(!$param->isOptional()){
  16.                
  17.             }
  18.         }*/
  19.  
  20.         //create an instance of an class without calling class's constructor
  21.         $object = unserialize(
  22.                 sprintf(
  23.                         'O:%d:"%s":0:{}', strlen($class), $class
  24.                 )
  25.         );
  26.  
  27.         if (is_array($array) && count($array) > 0) {
  28.             foreach ($array as $name => $value) {
  29.                 $name = strtolower(trim($name));
  30.                 if (!empty($name)) {
  31.                    
  32.                     if(method_exists($object, 'set'.$name)){
  33.                         $object->{'set'.$name}(Util::arrayToObject($value));
  34.                     }else{
  35.                         if(($strict)){
  36.                            
  37.                             if(property_exists($class, $name)){
  38.                                
  39.                                 $object->$name = Util::arrayToObject($value);
  40.                                
  41.                             }
  42.  
  43.                         }else{
  44.                             $object->$name = Util::arrayToObject($value);
  45.                         }
  46.                        
  47.                     }
  48.  
  49.                 }
  50.             }
  51.             return $object;
  52.         } else {
  53.             return FALSE;
  54.         }
  55.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement