luoziluojun
luoziluojun

Reputation: 126

PHP object Operator Precedence (->)

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'

Upvotes: 4

Views: 538

Answers (3)

Radical
Radical

Reputation: 1073

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?

Upvotes: 5

delboy1978uk
delboy1978uk

Reputation: 12365

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.

Upvotes: 1

OnekO
OnekO

Reputation: 41

What about echo ($a->$b)['f'];?

Upvotes: -4

Related Questions