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};
$user->{$value}
tries to access the property called "foo->bar" (no, not the property "bar" on the property "foo", but the property called "foo->bar") on$user
…$user->{$value}
means$user->{"foo->bar"}
?$o->$p
(same thing with or without{}
) means you're accessing one direct property on$o
, not a nested chain.