user5332
user5332

Reputation: 774

Can't access object property by array value

I didnot understand why this is not working in PHP 7.0

$obj = mysqli_fetch_object(...);
if (is_object($obj)) { // OK
 echo $obj->name;
 // writes Hello
 $my_var = "name";
 echo $obj->$my_var; 
 // writes Hello
 $my_arr = array('test' => array('col' => 'name'));
 echo $obj->$my_arr['test']['col']; // <-- this didnot work
 // writes nothing :( 
}

Could I anyway to correct it?

Upvotes: 0

Views: 33

Answers (1)

Siguza
Siguza

Reputation: 23830

-> is executed before [], so your code is equivalent to:

echo ($obj->$my_arr)['test']['col'];

You can change that with {}:

echo $obj->{$my_arr['test']['col']};

Upvotes: 1

Related Questions