<?php // 为了消除对 $a 反复赋值的影响,稍微改写一下楼主位的程序
$a = 1; $b = ($a + $a++); echo $b;
$c = 1; $d = ($c + $c + $c++); echo $d;
这就是典型的UB(undefined behavior,未定义行为)。php手册明确指出:
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.
简而言之:如果同一个语句中“求值”与“修改”同时出现,那么其执行顺序没有任何保证。
所以对于上边的程序,$b 得 2 或 3 都是对的,$d 得 3 或 4 都是对的。
事实上这个程序在不同的PHP版本下,就可以测试出不同的结果:
(以下结果来自于 http://sandbox.onlinephpfunctions.com/)
- 对于 PHP 7.1.0 ,
$b得 3 ,$d得 3 - 对于 PHP 4.4.9 ,
$b得 2 ,$d得 3
<?php // 为了消除对 $a 反复赋值的影响,稍微改写一下楼主位的程序
$a = 1; $b = ($a + $a++); echo $b;
$c = 1; $d = ($c + $c + $c++); echo $d;
这就是典型的UB(undefined behavior,未定义行为)。php手册明确指出:
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.
简而言之:如果同一个语句中“求值”与“修改”同时出现,那么其执行顺序没有任何保证。
所以对于上边的程序,$b 得 2 或 3 都是对的,$d 得 3 或 4 都是对的。
事实上这个程序在不同的PHP版本下,就可以测试出不同的结果:
(以下结果来自于 http://sandbox.onlinephpfunctions.com/)
- 对于 PHP 7.1.0 ,
$b得 3 ,$d得 3 - 对于 PHP 4.4.9 ,
$b得 2 ,$d得 3
$a = 1;
$b = $a + $a++;
$b = 2 + 1;
echo $b;
$a = 1;
$c = $a + $a + $a++;
$c = 2 + 2+ 1;
echo $c;
????
@王东哲 指的是一条语句之内,各个部分的执行顺序。例如 $b = $a + $a++; 这一条语句就有4个行为:
- 求
+左侧的值:取$a - 求
+右侧的值:取$a,之后$a自增 - 运算
$b赋值。
其中只有3和4的顺序是确定的,1、2的顺序不能保证。
关于 LearnKu
推荐文章: