0

I keep on stumbling on this PHP quirk and can't seem to explain myself why it's happening.

Why does this

new MyClass()->doSomething();

Trigger an error, while

(new MyClass())->doSomething();

and

$myObject = new MyClass();
$myObject->doSomething();

work as expected?

Is there a valid reason for needing the brackets around the constructor?

I found this RFC explaining that it was a conscious choice, but I still can't seem to understand the reason for it.

Raibaz
  • 9,280
  • 10
  • 44
  • 65

3 Answers3

2

It seems just a design decision: https://wiki.php.net/rfc/instance-method-call

Moreover works well with function call chaining (https://wiki.php.net/rfc/fcallfcall) and dereferencing

Here the full discussion on PHP Internals ML: https://www.mail-archive.com/internals@lists.php.net/msg48787.html

1

MyClass() could be a function call which returns an object whose doSomething method returns a string which refers to a class which you're then trying to instantiate with new, i.e.:

$className = MyClass()->doSomething();
new $className;

The added () are for syntactical disambiguation.

deceze
  • 510,633
  • 85
  • 743
  • 889
-1
new MyClass

returns a pointer on MyClass object then you can access your method like that

(new MyClass())->func();

because of the pointer

here

new MyClass()->func();

you don't access the pointer, then can't use your function and that's why you get an error

RomMer
  • 909
  • 1
  • 8
  • 19