-1

I have an object and need to access an attribute from a string like this:

$string = 'items[0]->sellers[0]->commertialOffer->Price';

I've tried something like this but it doesn't work:

$myObject->{$string};

Any idea?

tereško
  • 58,060
  • 25
  • 98
  • 150
pablo
  • 121
  • 2
  • 10
  • Sounds like an XY problem. I can't imagine any good reason for having a string like that. – Devon Bessemer Jun 20 '18 at 22:11
  • This has nothing to do with OOP (I removed the tag). Could it be, that you are actually just unaware of the **second parameter** in `json_decode()`? – tereško Jun 20 '18 at 23:01

3 Answers3

0

Are you passing the string between two functions ? If yes , then take 4 values and create the string like :-

$string = $value1.'|'.$value2.'|'.$value3.'|'.$value4 ;

Then explode the string and get back the 4 values .

0
$items = '{"items":[{"sellers":[{"commertialOffer":{"Price":33}}]}]}';
$myObject = json_decode($items);
$string = 'items[0]->sellers[0]->commertialOffer->Price';
echo ($myObject->{'items'}[0]->{'sellers'}[0]->{'commertialOffer'}->{'Price'});
echo ($myObject->items[0]->sellers[0]->commertialOffer->Price);

As $myObject->items is an array you can`t access it like

$string = 'items[0]';
echo $myObject->{$string};

You can access that by using

$string = 'items';
echo $myObject->{$string}[0];
-1

You probably want to revise your problem because interpreting raw code from a string is often a bad idea. You could potentially use the eval function: see. Again, this is probably not a good idea: when is eval evil?

markvdlaan93
  • 613
  • 10
  • 26