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.

3
  • stackoverflow.com/questions/1402505/… Commented Apr 14, 2017 at 8:49
  • @Ananth, that doesn't answer the question at all. Commented Apr 14, 2017 at 8:50
  • new MyClass() actually return a pointer on MyClass() Commented Apr 14, 2017 at 8:57

3 Answers 3

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/[email protected]/msg48787.html

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.