Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

php - Call function directly after constructor: new Object()->callFunction()

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...