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