有人可以帮助我理解这段代码吗,因为它似乎不遵循 PHP 中递增/递减运算符的优先级和关联性原则:(这是来自 PHP 手动递增/递减运算符页面中的评论 - http://php.net/manual/en/language.operators.increment.php )
第一个例子 -
$a = [ 0, 1, 2 ];
$i = 0;
$a[$i++] = $i;
var_dump( $a );
/* 这是输出:
array (size=3)
0 => int 1
1 => int 1
2 => int 2
这是我对正在发生的事情的解释:
1. Array index gets calculated, so $a[$i++] is $a[0]
2. Then rval gets calculated (which after $i++ in the step above) is now 1
3. The value of the expression gets calculated which is 1.
到目前为止一切顺利。 */
第二个例子 -
$a = [ 0, 1, 2 ];
$i = 0;
$a[$i] = $i++;
var_dump( $a );
/* 这是输出:
array (size=3)
0 => int 0
1 => int 0
2 => int 2
这是我对正在发生的事情的解释:
1. The array index gets calculated which should be 0 ($a[0]), but ACTUALLY it is 1 ($a[1])
2. The rval gets calculated , which is $i++ , so the value now is 0.
3. The expression value gets calculated , which should be 1 after $i++ in the step above, but ACTUALLY it is 0.
所以从根本上来说,我无法理解上面第二个示例中的步骤 1 和 3。 */
最佳答案
来自与您的代码相同的注释:
Assignment index expressions and value expressions are both evaluated before any actual assignment happens, that means that no mater where you place your post incr/decr you may not be getting the result you had in mind.
上线$a[$i++] = $i;
,都是索引表达式 $i++
关于 LHS 和值表达式 $i
在分配之前正在对 RHS 进行评估。
关于php - PHP 中递增/递减运算符的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14078415/