"Operator"优先级?为什么 new Object()->method() 在 PHP 中给出语法错误?

"Operator" precedence? Why new Object()->method() gives a syntax error in PHP?

让我们考虑以下代码:

<?php

class X{
    public function test(){
        return 'test';
    }
}

//This obviously works:
$x = (new X())->test();
//This does not, syntax error
$x = new X()->test();
echo $x;

为什么?

顺便说一句: 我知道它是在 php 5.4

中引入的

这不是关于 "how",而是关于“为什么”——我知道第一个语法是手册中记录的语法。实际上,更多的是关于在哪里以及如何找到答案。

根据我目前所学,同时在别处提问:

-> 实际上不是 "operator",而是 "token" 或 "lexical token" - 这对我帮助不大。

第一个版本等于说:"new (DateTime()->format())" 这显然是错误的。这表明它是关于 "operator precedence",但是 #1 - -> 不是运算符(对吗?),以及 #2 - 为什么没有在任何地方记录它?

顺便说一句,在 http://php.net/manual/en/language.operators.precedence.php we can read that the "new" operator associativity is neither left nor right, it's none, and we can also read "Operators of equal precedence that are non-associative cannot be used next to each other, for example 1 < 2 > 1 is illegal in PHP" so... if -> was an operator (and it was non-associative) then everything would be clear, but is it an operator? If it is, then why isn't it listed on the above list ( http://php.net/manual/en/language.operators.precedence.php 上)?

因为它是模棱两可的,即它可以用两种不同的方式解释:

  • 在新的 X 实例(您想要的实例)上调用 test()

    $object = new X();
    $x      = $object->test();
    
  • function X() 返回的对象上创建方法 test() 返回的 class 名称的新实例]:

    $object = X();
    $class  = $object->test();
    $x      = new $class();
    

奇怪的是,实际上没有办法为第二种情况写一条线......下面的行不通:

new (X()->test());   // syntax error
new (X()->test())(); // syntax error

不过,你还是明白了。