“操作员"指的是“操作员".优先?为什么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中引入的
BTW: I know it was introduced in php 5.4
这与如何"无关,而与"为什么"有关-我知道第一种语法是手册中记录的语法.实际上,更多的是关于在哪里以及如何找到答案.
It's not about "how", it's about "why" - I know the first syntax is the one documented in the manual. Actually, it's more about where and how to find the answer.
根据我到目前为止所学的知识,同时在其他地方提问:
From what I've learned so far, while asking my questions elsewhere:
->实际上不是一个运算符",它是一个令牌"或词汇令牌"-对我没有多大帮助.
The -> is not actually an "operator", it's a "token" or "lexical token" - which doesn't help me much.
第一个版本等于说:"new(DateTime()-> format())",这显然是不好的.这表明它是关于运算符优先级"的,但是#1-->不是运算符(对吗?),以及#2-为什么没有在任何地方对此进行记录?
The first version is equal to saying: "new (DateTime()->format())" which obviously is bad. This suggest it's about "operator precedence", but #1 - the -> is not an operator (right?), and #2 - why isn't this documented anywhere?
BTW,在 http://php.net/manual/zh/language.operators.precedence.php 中,我们可以看到新"运算符的关联性既不左也不右,都不是,我们还可以阅读不能在同等优先级的非关联运算符旁边使用"彼此之间,例如1< 2> 1在PHP中是非法的",因此...如果->是 operator (并且是非关联的),那么一切都会很清楚,但是是吗?操作员?如果是,那么为什么它不在上面的列表中列出( http: //php.net/manual/en/language.operators.precedence.php )?
BTW, on 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 )?
推荐答案
由于模棱两可,因此可以用两种不同的方式进行解释:
Because it's ambiguous, i.e. it can be interpreted in 2 different ways:
-
在新的
X
实例(您想要的实例)上调用test()
:
Call
test()
on a newX
instance (the one that you want):
$object = new X();
$x = $object->test();
在 function X()
:
$object = X();
$class = $object->test();
$x = new $class();
奇怪的是,实际上没有办法为第二种情况编写单行代码……以下内容将不起作用:
Strangely enough, there's actually no way to write a one-liner for the second case ... the following won't work:
new (X()->test()); // syntax error
new (X()->test())(); // syntax error
但是,您仍然知道.
这篇关于“操作员"指的是“操作员".优先?为什么new Object()-> method()在PHP中给出语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!