Access object variables dynamically in php -
there multiple response type service provider , why created config array below.
$configarray = array( 'type_1' => array( 'name' => array('parent', 'user', 'profile', 'name', 'fullname') ), 'type_2' => array( 'name' => array('parent', 'person', 'info', 'basic', 'name') ) );
so if return type 'type 1' object path of variable 'name' $obj->parent->user->profile->name->fullname
, same type 2 $obj->parent->person->basic->name
my question is, correct implementation in php set object path dynamically ? right now, plan implement below.
$path = ''; foreach($configarray[$type]['name'] $chunks ){ if($path != ''){ $path .= '->'; } $path .= $chunks; }
it helpful if can suggest standard method.
thanks in advance, tismon varghese
you can achieve using eval(), not recommend method prone remote code execution if input coming externally:
$path = ''; foreach($configarray['type_1']['name'] $chunks ){ $path .= '->'.$chunks; } // $config have value of $obj->parent->user->profile->name->fullname eval('$config = $obj'.$path.';');
instead can loop through each given object in object path , can check if property exists in object:
// $obj root object foreach($configarray[$type]['name'] $prop) { if (!is_object($obj)) break; if (property_exists($obj, $prop)) { $obj = $obj->$prop; } } // have value of $obj->parent->user->profile->name->fullname print_r($obj);
Comments
Post a Comment