0

I know how PHP dynamic vars work, I know I can access object property like $object->{'somethingWith$var'}; or like $object->$var;

But what I try to accomplish is to access $object->property->subproperty from $object and the string $string = 'property->subproperty';.

I tryed $object->$string, $object->{$string}, $object->$$string hahaha, none worked.

Does anybody know how to do this ? :)

0

3 Answers 3

4

You can write simple function, something like this:

function accessSubproperty($object, $accessString) {
    $parts = explode('->', $accessString);
    $tmp = $object;
    while(count($parts)) {
        $tmp = $tmp->{array_shift($parts)};
    }
    return $tmp;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this is what I think is the best then. I will rather use the foreach approach suggested by nl-x bellow for I will use it only once, but the idea is here and you were first. Thanks.
2

There is no way to do this like that.

You have to first assign $property = $object->$propertyName and then access var you wanted to $property->$subpropertyName.

In your examples string property->subproperty will be treated like variable name which obviously doesn't exist.

1 Comment

Ok, thank you for the explanation and fast answer, I was looking for a solution though. also, I usually can access directly $object->property->subproperty without assignment, or I didn't get what you meant :)
1

It is not working because all you are accomplishing with your tries is getting $object{'property->subproperty'} which off course is not the same as $object->{'property'}->{'subproperty'}.

What you can do is:

$ret = $object;
foreach (explode("->",$string) as $bit)
    $ret = $ret->$bit;

Or you will have to go to the ugly and evil eval() (let the downvoting start):

eval("return \$object->$string;")

3 Comments

The only things this adds to Brabec's answer is the fact that you could use eval which is really not a great suggestion because of the security implications.
I appreciate the foreach way, and will use it. I don't rely on eval 0:) Thanks
@disadb So you used the answer, but accepted the other answer :) ?

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.