How can I access a deep object property named as a variable (dot notation) in php?
It is very easy to reduce the object path using variable property notation ($o->$p
):
$path = 'foo.bar';
echo array_reduce(explode('.', $path), function ($o, $p) { return $o->$p; }, $user);
This could easily be turned into a small helper function.
A little improvement added to @deceze post.
This allow handling cases where you need to go through arrays also.
$path = 'foo.bar.songs.0.title';
echo array_reduce(explode('.', $path), function ($o, $p) { return is_numeric($p) ? $o[$p] : $o->$p; }, $user);
Edit:
And if you have PHP 7+, then the following will safely return null if a property's name is mistyped or if it doesn't exist.
$path = 'foo.bar.songs.0FOOBAR.title';
echo array_reduce(explode('.', $path), function ($o, $p) { return is_numeric($p) ? ($o[$p] ?? null) : ($o->$p ?? null); }, $user);