调用函数后直接构造函数:new Object() - > callFunction() [英] Call function directly after constructor: new Object()->callFunction()

查看:182
本文介绍了调用函数后直接构造函数:new Object() - > callFunction()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如你在标题中看到的,我的编程背景是Java。在Java中,你可以这样做

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.

现在在PHP我尝试做同样的事情。

Now in PHP i try to do the same

new Object()->callSomeMethod();

但在这里我得到一个'解析错误:语法错误,意外' - >'(T_OBJECT_OPERATOR) 。

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

有什么方法可以在PHP中做到这一点吗?

推荐答案

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

将在PHP 5.4中使用

will work in PHP 5.4+

EDIT

这是一个新功能添加到PHP 5.4:

It is a new feature added on PHP 5.4:


添加了类成员访问实例化,例如(new Foo) - > bar()

EDIT2

PHP功能RFC 建议两组语法(带&无括号),两者都是在RFC中实现,但只有一个已经发货。我找不到解释决定的链接。

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.

让我们来看看RFC中的无括号语法示例:

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


  • new foo-> bar()应读为(new foo) - > bar )

  • new $ foo() - > bar 应为(new $ foo()) - > bar

  • new $ bar-> y ; x 应为 (new($ bar-> y)()) - > x

  • 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.

这篇关于调用函数后直接构造函数:new Object() - > callFunction()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆