antoni
antoni

Reputation: 5546

PHP dynamic var from string

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 ? :)

Upvotes: 0

Views: 112

Answers (3)

nl-x
nl-x

Reputation: 11832

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;")

Upvotes: 1

Jiří Brabec
Jiří Brabec

Reputation: 298

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;
}

Upvotes: 4

Elon Than
Elon Than

Reputation: 9765

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.

Upvotes: 2

Related Questions