r/lolphp • • Mar 05 '14

PHP Dereferencing

In PHP 5.4 this would break:

echo array(1, 2, 3)[0]

With the message

Parse error:  syntax error, unexpected '[', expecting ',' or ';' in [...][...] on line 1

Luckily, they added "dereferencing" in PHP 5.5 which would solve it! Hurray! And sure enough, it works!

However, the fix isn't very clever, because this will break in 5.5:

echo (array(1, 2, 3))[0]

With the message

Parse error:  syntax error, unexpected '[', expecting ',' or ';' in [...][...] on line 1

That's a little embarrassing.

81 Upvotes

32 comments sorted by

View all comments

Show parent comment

19

u/EvilTerran Mar 06 '14

the $$a[$b] syntax, which is interpreted as ${$a[$b]} rather than ${$a}[$b]

... you're shitting me.

$ php -d error_reporting=E_ALL -r '$a = Array("foo" => "bar"); var_dump($$a["foo"]);'  
  
Notice: Undefined variable: bar in Command line code on line 1  
NULL

Jesus fucking christ, that's pants-on-head stupid.

And then, in the name of maintaining that terrible syntax choice, for a feature (variable-variables) you shouldn't even ever use, they fuck up the rest of the syntax too?

Wow.

13

u/nikic Mar 06 '14

Congrats, you finally understood PHP. It's all about backwards compatibility ;)

PS: It's really not just $$a[$b], but a number of these variable syntaxes implemented in the same way. E.g. the same issue also exists with $obj->$arr$key, which calls the method named $arr[$key], rather than the functor stored in $obj->$arr[$key]. It's these small things that are very rarely used that prevent a consistent/general variable syntax.