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! ;) )?

Marcus Kober
  • 106
  • 9
  • If it works why would you want to improve it. – Stijn Bernards Dec 18 '14 at 14:33
  • There's no urgent need to change it. But it seems to be a little bit complicated and not very elegant. – Marcus Kober Dec 18 '14 at 14:42
  • In addition, this is part of a very complex script and execution time is a relevant point here... – Marcus Kober Dec 18 '14 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); } – OIS Dec 18 '14 at 15:02
  • Thank you! The more I think about it, the more I think there's really no "prettier" way. ;) – Marcus Kober Dec 18 '14 at 15:11
  • So am I understanding this correctly, `p1` and `p2` are both objects and `p3` is a property for a value `string`. How complicated a script becomes depends on its design and its true, the reason your questioning here, to find better solutions or more appropriate designs. By the looks if it, this is horrible. How are `p1` and `p2` being instantiated and what is the relevance/relations between `p2` and `p1`, also `p1` and `$obj`? – dbf Dec 18 '14 at 21:07

1 Answers1

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?

Tomasz Racia
  • 1,786
  • 2
  • 15
  • 23
  • 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. – Marcus Kober Dec 18 '14 at 14:59