Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a deep object property named as a variable (dot notation) in php?

Tags:

properties

php

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};
like image 543
GiamPy Avatar asked Jan 11 '17 15:01

GiamPy


2 Answers

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.

like image 75
deceze Avatar answered Nov 18 '22 11:11

deceze


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);
like image 38
asiby Avatar answered Nov 18 '22 10:11

asiby