9

As you might have seen in the title, my programming background is Java. In Java you can do stuff like this

new Object().callSomeMethod();

without assigning the created Object to a variable, very useful and clear coding if you only need this Object once.

Now in PHP i try to do the same

new Object()->callSomeMethod();

but here i get a 'Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR)'.

Is there a way to do this in PHP ?

5
  • 1
    Only in PHP >= 5.4 e.g. echo (new DateTime())->format('d-M-Y'); Commented Sep 18, 2013 at 13:20
  • Declare the method static? Object::callSomeMethod(); Commented Sep 18, 2013 at 13:21
  • @MarkBaker Nope. I've seen in 5.4 Commented Sep 18, 2013 at 13:23
  • Static is not an option, it has to be an object :) @MarkBaker Thanks, this is what i searched for Commented Sep 18, 2013 at 13:25
  • @Basti - accept Kita's answer then, as he's given the correct solution Commented Sep 18, 2013 at 13:27

1 Answer 1

20
(new Object())->callSomeMethod();

will work in PHP 5.4+

EDIT

It is a new feature added on PHP 5.4:

Class member access on instantiation has been added, e.g. (new Foo)->bar().

EDIT2

The PHP feature RFC proposes two sets of syntax(with & without brackets), both of them are implemented in the RFC, but only one has been shipped. I couldn't find links explaining the decision.

Let's take a look at the bracketless syntax examples in the RFC:

  • new foo->bar() should be read as (new foo)->bar()
  • new $foo()->bar should be read as (new $foo())->bar
  • new $bar->y()->x should be read as (new ($bar->y)())->x

I think bracketless syntax is not shipped because its proposed parsing precedence is not very intuitive(hard to follow by eyes) as shown in the 3rd example.

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

3 Comments

Why does PHP not allow the syntax as mentioned by OP?
Can you include information about why the parentheses are neccessary? According to the operator precedence list, new has highest precedence, but -> occurs nowhere in this list...
Thanks, but this doesn't address my question why the parens are neccessary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.