The method invocation operator, and expressions, in PHP

PHP is a weird language.

$x = new Foo();
print $x->bar();

works fine as you'd expect. but

print new Foo()->bar();
print (new Foo())->bar();

all do not work.

I do not understand how you can build an expression parser, where the code above works, and the code below does not. It's almost as if $x = new XXX(xxx) a separate case searched for by the parser?

I mean if you have an expression parser capable of handling brackets, i.e. (1+2)*4, and you have the expression (new Foo()) and you have the concept of $object->method() then how can it possibly not work?

$ cat -n x.php
     1  <?php
     2
     3  class Foo {
     4     function bar() { return 4; }
     5  }
     6
     7  $foo = new Foo();
     8  print $foo->bar();
     9
    10  print (new Foo())->bar();

$ php -e x.php
Parse error: syntax error, unexpected T_OBJECT_OPERATOR 
in /home/adrian/x.php on line 10
P.S. I recently created a nerdy privacy-respecting tool called When Will I Run Out Of Money? It's available for free if you want to check it out.

This article is © Adrian Smith.
It was originally published on 1 Jun 2011
More on: FAIL | PHP | Language Design