There are many questions similar to this, however this is slightly different since it's about deep object property access, not just one level of depth.
Let's say I have a variable containing the string foo.bar
.
$user = new User();
$user->foo = new Foo();
$user->foo->bar = "Hello World";
$variable = "foo.bar"
I would like to echo $user->foo->bar
by making use of $variable
:
echo $user->foo->bar
This is what I have tried so far but with no success (it says NULL):
$value = str_replace(".", "->", $value);
echo $user->{$value};
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With