Advertisement
Guest User

Set Recursive PHP Properties

a guest
Aug 28th, 2015
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.13 KB | None | 0 0
  1.  
  2. function getRecursiveProperty( $object, $path ) {
  3.  
  4.   $array = explode( '->', $path );
  5.  
  6.   if ( empty( $array ) ) {
  7.  
  8.     return NULL;
  9.  
  10.   }
  11.  
  12.   foreach ($array as $i => $property) {
  13.  
  14.     if( is_numeric( $property ) ) {
  15.  
  16.         $object = $object[ intval( $property ) ];
  17.  
  18.     } else {
  19.  
  20.         if( ! isset( $object->$property ) ) {
  21.  
  22.             return NULL;
  23.  
  24.         } elseif( ! is_object( $object->$property ) && ! is_array( $object->$property ) ) {
  25.  
  26.             return $object->$property;
  27.  
  28.         } else {
  29.  
  30.             $object = $object->$property;
  31.  
  32.         }
  33.  
  34.     }
  35.  
  36.   }
  37.  
  38.   return $object->$property;
  39.  
  40. }
  41.  
  42. function setRecursiveProperty($object, $path, $value) {
  43.  
  44.     $array = explode('->', $path);
  45.  
  46.   foreach ( $array as $i => $property) {
  47.  
  48.     if( is_numeric( $property ) ) {
  49.  
  50.         $object = $object[ intval( $property ) ];
  51.  
  52.     } else {
  53.  
  54.         if ( ! isset( $object->$property ) ) {
  55.  
  56.           return FALSE;
  57.  
  58.         } elseif ( ! is_object( $object->$property ) && ! is_array( $object->$property ) ) {
  59.  
  60.           $object->$property = $value;
  61.  
  62.           return TRUE;
  63.  
  64.         }
  65.  
  66.         $object = $object->$property;
  67.  
  68.     }
  69.  
  70.  
  71.   }
  72.  
  73.   return FALSE;
  74.  
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement