5

Can I get to work a code like:

    new \Controllers\ServiceController()->fbdump();

so I won't have to create a var just to execute a single method?

1 Answer 1

6

Yes, but you need to add a set of parenthesis, since -> has higher precedence than new:

(new \Controllers\ServiceController)->fbdump();
4
  • Hmm, intresting. Why? Jan 8, 2016 at 20:21
  • @Zhigalin If you don't add the parenthesis it will parse it as new ( \Controllers\ServiceController->fbdump() ); which won't work.
    – Paul
    Jan 8, 2016 at 20:30
  • But why? Why '->' has lesser priority than 'new'? Jan 10, 2016 at 9:21
  • 1
    @Zhigalin I'm not sure, other than that's just how the, Zend engine, at least, works. It probably was a decision they made way back when they were first working on PHP 4, and just hasn't changed since then. As far as I can tell, it's not even documented anywhere, so the behaviour without parenthesis might change at some point or work differently in some engines and not others. The behaviour with parenthesis should always be well-defined though.
    – Paul
    Jan 10, 2016 at 16:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.