Skip to content
Advertisement

PHP – Accessing a object property from dynamic variable

I’m looking for accessing a property of a object property of an object like this :

$property = "user->name";
echo $object->$property; // ??, I want $object->user->name

I tried a lot of things, but none seems work.

Thanks

Advertisement

Answer

I don’t think you can make multiple dereferences this way. You’ll be looking for a variable in $object called user->name. Instead, you can split by -> and then make multiple calls, something like:

$test = 'user->name';
$val = $object;
foreach(explode('->', $test) as $item) {
  $val = $val->$item;
}
echo $val;   # This is the result of $object->user->name

Sample Code

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement