Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP object Operator Precedence (->)

Tags:

php

I write some code:

class a{
    public $b=['f'=>'c'];
}
$a=new a;
$b='b';
echo $a->$b['f'];

When I use cli,it output 'c',but when I use apache http server,throw an errorIllegal string offset 'f',so I don't know which precedence is higher between -> and [.There is no introduction about -> on http://php.net. My PHP version is 5.6 and use windows 10.In Linux cli and httpd will output 'c'

like image 995
luoziluojun Avatar asked Sep 08 '25 07:09

luoziluojun


2 Answers

For a general idea of the precedence order between -> and [, you might want to take a look at the PHP7 migration documentation here. I know you are talking about PHP5, but the migration documents pays attention to this since the behaviour was changed between PHP5 and PHP7.

To answer your question, $foo->$bar['baz'] is interpreted as $foo->{$bar['baz']} in PHP5. This means your code should be throwing an error because it is trying to access $b['f'] while it is using $b='b'; as the definition of $b.

However, in PHP7 it is interpreted as ($foo->$bar)['baz'], so here it should be working as you expect.

Are you sure your CLI isn't using PHP7?

like image 100
Radical Avatar answered Sep 10 '25 03:09

Radical


Your code is almost right - just get rid of that second $!

class a{
    public $b=['f'=>'c'];
}
$a=new a;
$b='b';
echo $a->b['f']; // without the $ it works
$x = $a->$b;  // otherwise you need to assign first
echo $x['f']; // now it works
echo $a->{$b}['f']; // or wrapped in curlies

see here https://3v4l.org/gZJWt

The precedence is given to $. In other words, $x->$b['f'] considers $b first to be an array, so it looks for $b['f'] which doesn't exist, hence your error. Putting the curly brackets around $b forces PHP to evaluate that first, giving you the value 'b', so it then becomes $x->b['f'], which exists and thus works.

like image 21
delboy1978uk Avatar answered Sep 10 '25 02:09

delboy1978uk