elb
elb

Reputation: 177

PHP - Dynamically reference object property

I have code like :

$result = $object->property[0];

but I want to do something like :

if ($a) {  
  $property = 'blue' }  
else {  
  $property = 'black'}  
$result = $object->$property[0];

However this give me a Cannot use string offset as an array error.

Any pointers (no pun intended) appreciated.

Upvotes: 2

Views: 1473

Answers (2)

som
som

Reputation: 4656

$result = $object->{$property}

Upvotes: 0

Dmitry Teplyakov
Dmitry Teplyakov

Reputation: 2898

Use braces:

$result = $object->{$property}[0];

Upvotes: 6

Related Questions