在PHP 5.2中,为什么实例化一个类并在同一行调用一个方法是无效的


In PHP 5.2 why is instantiating a class and calling a method on the same line invalid?

这就是我想做的:

$app = (new Factory())->GetApp();

但是,我得到了一个"意外的T_OBJECT_OPERATOR"错误。

为了避免这种情况,我必须做:

$Factory = new Factory();
$app = $Factory->GetApp();

为什么这是必要的?如果有什么不同的话,我正在运行PHP 5.2。

这是一个有点重复的答案,但这是因为PHP 5.2不支持这样做。

然而,它是在PHP 5.4中-请参阅http://www.php.net/manual/en/migration54.other.php

在实例化时添加了类成员访问(例如(new foo)->bar())支持

您也可以这样做:

class MyClass {
  public static function init(){
    return new self();
  }
  ....
}

然后你可以这样使用:

MyClass::init()->doStuff()->Whatever();

在我看来,这比使用要好一点

(new Myclass())->doStuff()->Whatever();