I really don’t know what you mean

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.

4 Responses to “I really don’t know what you mean”

  1. I think it’s accidently by design ;)

    It’s know, and apparently might be supported in PHP6.

    • Owen Jacobson says:

      Ooh. Is there a bug for this somewhere? Searching the PHP bugs database for “array” or “index” is a lot time consuming.

  2. seutje says:

    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

    • Owen Jacobson says:

      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.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped=""> (Syntax highlighting)