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
     3  class Foo {
     4     function bar() { return 4; }
     5  }
     7  $foo = new Foo();
     8  print $foo->bar();
    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

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=""> <s> <strike> <strong>

For inserting HTML or XML please remember to use &lt; instead of <