Reputation: 5546
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
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
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
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