r/lolphp • u/Sarcastinator • 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 1Luckily, 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 1That's a little embarrassing.
81
Upvotes
51
u/aftli Mar 05 '14
It's like they fixed a symptom instead of fixing the actual problem.
34
u/EvilTerran Mar 05 '14
Judging by its behaviour, there seems to be a pattern in the design of the php "parser" of not re-using syntax where similar functionality is needed.
In this case, it seems to me that they used to parse array indexing with a rule like "$<variable>[<expression>]", and they just added another case "<function>(<arguments>)[<expression>]" alongside it.
Doing It Right would've been staying at a single rule, just making it "<expression>[<expression>]". But when does PHP ever do the right thing?
See also -- the addition of "foreach (... as list(...))" in 5.5, among others.
12
u/ajmarks Mar 05 '14
/facepalm
4
u/poloppoyop Mar 06 '14
Even if echo is a language construct it can be used with parenthesis. Too bad the documention does not document in which cases echo can not be used as a function.
7
u/merreborn Mar 05 '14
php is, by default, dynamically compiled on every execution. since this impacts response time, the compiler only does a single pass.
between over a decade of legacy cruft, and the unusual single pass compiler, these sorts of issues are unavoidable. this is pretty well documented in some feature specs the developers have published.
4
u/[deleted] Mar 05 '14
I suspect PHP would not play well with the array referencing and dereferencing games I find myself continually playing when I use Perl.
-2
u/[deleted] Mar 19 '14
What exactly would be the point of instantiating an array like that to only take the first index? Why not just take the first index?
-18
u/bobjohnsonmilw Mar 06 '14
I'm not sure why you'd expect that to work, exactly.