It’s Monday, and I’m sick, so you get some low-hanging fruit today. The following snippet produces a syntax error in PHP:
1 2 3 4 5 6 7 | <?php function monolithic_dimensions() { return array(1, 4, 9); } print monolithic_dimensions()[0]; // syntax error, unexpected '[' ?> |
Of course, it’s trivial to work around:
1 2 3 4 5 6 | <?php /* ... */ $temp = monolithic_dimensions(); print $temp[0]; // Prints 1 ?> |
In almost every other language with array-indexing syntax, any expression can be indexed if it evaluates to an array. Consider Python:
1 2 3 4 | def monolithic_dimensions(): return [1, 4, 9] print monolithic_dimensions()[0] # Prints 1 |
Or Ruby:
1 2 3 4 5 | def monolithic_dimensions return [1, 4, 9] end print monolithic_dimensions()[0] # Prints 1 |
Or even C:
1 2 3 4 5 6 7 8 9 10 | #include <stdio.h> int const *monolithic_dimensions() { static int const dimensions[] = {1, 4, 9}; return dimensions; } int main() { printf("%d\n", monolithic_dimensions()[0]); /* Prints 1 */ } |
Of course, since there’s no formal language spec for PHP, there’s no way to know whether this is by design or by accident.
I think it’s accidently by design ;)
It’s know, and apparently might be supported in PHP6.
Ooh. Is there a bug for this somewhere? Searching the PHP bugs database for “array” or “index” is a lot time consuming.
what really intrigues me is that
function foo() {
$bar = new stdClass();
$bar->baz = 'meh';
return $bar;
}
print foo()->baz; // prints 'meh'
seems to work fine
That’s probably a consequence of PHP’s “organic” development: array indexing has existed for most of PHP’s life, while the
->dereference operator was introduced in PHP 4, when the PHP community had started to grok the idea that expressions should be interchangable.