PHP 求幂运算符优先级

PHP exponentiation operator precedence

我阅读了 PHP.net docs,其中指出:

Operator ** has greater precedence than ++.

但是当我 运行 这段代码时,我得到了意外的输出:

<?php
$a = 2;
echo(++ $a ** 2); 
// output: 9, means: (++$a) ** 2
// expected: 5, means: ++($a ** 2)

你能帮我弄清楚为什么会这样吗?谢谢!

这是因为++$a是前置增量,而$a++是post增量。

您可以阅读更多相关内容here

此外,

Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.

From: PHP Operator Precedence

空格,这是为什么!

++ $a ** 2不同于++$a ** 2,也就是不同于++$a**2

似乎发生的是 Post/Pre 增量是在操作之外计算的。所以执行 ** 并返回结果。

  • 对于 post 增量,$a 变量在操作后更新。
  • 对于预增量,$a 变量在操作前更新。

所以文档

Operator ** has greater precedence than ++.

我觉得有点奇怪。

经过一番搜索,评论中也提到了这一点: http://php.net/manual/en/language.operators.increment.php#119098

哦,在文档本身。

<?php
// POST
$a = 2;
echo($a ** 2);      // 4
echo(PHP_EOL);
echo($a++ ** 2);    // 9
echo(PHP_EOL);
echo($a);           // 3
echo(PHP_EOL);
echo(PHP_EOL);

// PRE
$a = 2;
echo($a ** 2);      // 4
echo(PHP_EOL);
echo(++$a ** 2);    // 4
echo(PHP_EOL);
echo($a);           // 3
echo(PHP_EOL);
echo(PHP_EOL);

我敢肯定,此处的文档有误。

Operator ** has greater precedence than ++.

这种说法似乎与分组遵循运算符优先级的方式相矛盾。

Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation.

事实上,如果我们在 ++ 之前分组 **,我们将获得 ++($a ** 2),就像问题中所述。但是这个表达式甚至是无效的,因为 ++ 运算符只能用于变量,不能用于表达式。

++ 仅对变量有效这一事实意味着没有具有两个操作数的运算符可以具有更高的优先级。