PHP Access nested object property via strings in array

Let's say we have an object $ obj. This object has a property that looks like this:

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

      

Now I am getting the structure of the nested property in the array:

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

      

I am currently using the following function to access the property:

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 this (no, "eval" is not an option !;))?

+3


source to share


1 answer


If you want to do it in one line, or a little 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 this the goal you want to achieve?

+2


source







All Articles