1

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

3
  • 1
    What ?? Can you explain briefly .. show your object Commented Feb 16, 2017 at 6:17
  • Possible duplicate of Dynamically access nested object Commented Feb 16, 2017 at 6:27
  • I don't think this is a duplicate, I can't use XPath as suggested because this is not XML, and I cannot access directly to what I want. To answer to M A SIDDIQUI, I need to store the property of an object as shown ($property) and reuse this variable on the $object object. Commented Feb 16, 2017 at 6:31

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

Shouldn't the first "$var" be a "$val"? . Apart from this, this raw statement works in my code: echo $json_dump->geometry[6]->obs[2]->hayabusa2->delay_from; But I cannot "simulate" it by assigning "geometry[6]->obs[2]->hayabusa2->delay_from" to $test and using your code, I get error "Notice: Undefined property: stdClass::$geometry[6] "
1

If you split your variable into 2 like so:

    list($property1, $property2) = explode('->', $property);

    echo $object->{$property1}->{$property2}; 

1 Comment

Less flexible, but more performant and highly legible. +1 for avoiding recursion.
0

Try the following :

$property = "user->name";

$prop_arr = explode('->',$property);
foreach ($prop_arr as $prop){
    $obj = $obj->{$prop};
}
echo $obj;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.