php - "$foo = 5 && $bar = 15"是如何评估的,为什么它不是错误?

标签 php operator-precedence associativity

假设我们有这样一个简单的代码:

// $foo and $bar aren't defined before

$foo = 5 && $bar = 15;

// var_dump()
// $foo is (bool) TRUE
// $bar is (int) 15

所以我假设它是这样工作的:

$foo = (5 && ($bar = 15))

但在我看来应该是:

$foo = ((5 && $bar) = 15) // should throw syntax error due FALSE = 15
  1. 评估表从左到右 [$foo 想要 5 但 && 更高]
  2. && 获得最高优先级 [所以 && 需要 5 和 $bar]
    • 5 == 真; $bar == Undefined [所以它是 NULL == FALSE]
  3. = 获得正确的关联性 [等待 (5 && $bar) 的计算]

请用最简单的方式(在其他一些例子中)向像我这样的穷人解释一下。问候。

最佳答案

我认为阅读此处的手册页有助于清除很多内容。

那么这是如何评估的呢?

$foo = 5 && $bar = 15;

首先你要知道&&的优先级高于=。所以第一个想法是:

$foo = (5 && $bar) = 15;

但现在是您必须阅读手册直到最后的时刻:http://php.net/manual/en/language.operators.precedence.php

引自那里:

Note: Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.

这是什么意思?

它默默地将 15 分配给 $bar 例如

$foo = (5 && ($bar = 15));

现在您可以评估 &&$bar get 赋值 15,5 && 15 为 TRUE,get 赋值给 $富

关于php - "$foo = 5 && $bar = 15"是如何评估的,为什么它不是错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28611707/

相关文章:

scala - 具有反向关联中缀表示法的柯里化(Currying)函数的部分应用语法

php - 如何设置表单的 DB 代码

c - 使用右移和左移运算符时的优先级

c++ - 是否保证不会对 if 语句进行不必要的评估?

c - C 中运算符优先级的奇怪结果

c++ - C/C++ 中的运算符优先级和关联性

c - C中函数调用运算符的结合性

php - 如何使用 linux 命令从日志文件中检索数据并添加到数组

php - 根据是否设置了 $bar 回显 foo

php - 模拟 Amazon FPS 沙盒上的错误