2

There are multiple response type from my service provider and that is why i created a config array like 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 the return type is 'type 1' object path of the variable 'name' is $obj->parent->user->profile->name->fullName and the same for type 2 is $obj->parent->person->basic->name

My question is, which is the correct implementation in php to set this object path dynamically ? Right now, my plan is to implement as below.

$path = '';
foreach($configArray[$type]['name'] as $chunks ){ 
  if($path != ''){ $path .= '->'; }
  $path .= $chunks;
}

It will be really helpful if someone can suggest a standard method.

Thanks in advance, Tismon Varghese

1
  • 2
    Don't let external input decide how to call object names without sanitizing the input. Otherwise your code is open for hacking attempts. The standard method is to have constructor functions, that disect the input and return an instantiated object. Commented Jun 15, 2015 at 6:42

1 Answer 1

1

You can achieve this by using eval(), however I will not recommend this method as it is prone to remote code execution if the input is coming externally:

$path = '';
foreach($configArray['type_1']['name'] as $chunks ){
  $path .= '->'.$chunks;
}
// $config will have value of $obj->parent->user->profile->name->fullName
eval('$config = $obj'.$path.';');

Instead you can loop through each given object in the object path and can check if the property exists in the object:

// Say $obj is your root object
foreach($configArray[$type]['name'] as $prop) { 
    if (!is_object($obj)) break;
    if (property_exists($obj, $prop)) {            
        $obj = $obj->$prop;
    }         
}

// This will have value of say $obj->parent->user->profile->name->fullName
print_r($obj);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ulver. Modified code as suggested since this seems reasonable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.