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