5

Let's say we have an object $obj. This object has a property which is as follows:

$obj->p1->p2->p3 = 'foo';

Now I get the nested property structure in an array:

$arr = array( 'p1', 'p2', 'p3' );

Currently I use the following function to access the property accordingly:

function getProperty( $obj, $property ) {
foreach( $property as $p ) {
  $obj = $obj->{$p};
 }
 return $obj;
}

$value = getProperty( $obj, $arr); // = 'foo'

Is there a smarter way to do that (no, 'eval' is not an option! ;) )?

6
  • If it works why would you want to improve it. Commented Dec 18, 2014 at 14:33
  • There's no urgent need to change it. But it seems to be a little bit complicated and not very elegant. Commented Dec 18, 2014 at 14:42
  • In addition, this is part of a very complex script and execution time is a relevant point here... Commented Dec 18, 2014 at 14:44
  • 1
    I don't think you can make it "prettier". Here is an alternative to foreach with array_reduce. function getProperty($object, array $keys) { return array_reduce($keys, function($carry, $item) { return $carry->{$item}; }, $object); } Commented Dec 18, 2014 at 15:02
  • Thank you! The more I think about it, the more I think there's really no "prettier" way. ;) Commented Dec 18, 2014 at 15:11

1 Answer 1

1

If you want to make it in one line or a bit prettier, you can try this:

echo json_decode(json_encode($obj), true)['p1']['p2']['p3']; // PHP 5.4

or for PHP 5.3:

$arr = json_decode(json_encode($obj), true);
echo $arr['p1']['p2']['p3'];

Is that the goal you want to achieve?

Sign up to request clarification or add additional context in comments.

1 Comment

Now that looks nice. ;) But the object can be very big with many properties. Have to check the execution time of encoding to and decoding from json.

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.