普通网友 2017-09-05 12:11
浏览 91
已采纳

具有递增的非直观表达式评估

For the following code

<?php

$a=1;   $b=$a++;              var_dump($b);
$a=1;   $b=$a+$a++;           var_dump($b);
$a=1;   $b=$a+$a+$a++;        var_dump($b);
$a=1;   $b=$a+$a+$a+$a++;     var_dump($b);
$a=1;   $b=$a+$a+$a+$a+$a++;  var_dump($b);

I obtained this result:

int(1)
int(3)
int(3)
int(4)
int(5)

I expected 1,2,3,4,5 rather than 1,3,3,4,5. Why after $a=1; $b=$a+$a++; we obtain $b=3?

PHP 7.1.5-1+deb.sury.org~xenial+1 (cli) (built: May 11 2017 14:07:52) ( NTS )

  • 写回答

3条回答 默认 最新

  • douguomou5094 2017-09-05 12:43
    关注
    $a=1;   $b=$a+$a++;           var_dump($b);            // int(3)
    

    You assumed that the expression above is evaluated from left to right as follows (temporary variables $u and $v are introduced in the explanation for clarity):

     $a = 1;
     $u = $a;              //    ($a)   the LHS operand of `+`
     $v = $a;              //  \ ($a++) the RHS operand of `+`
     $a ++;                //  /
     $b = $u + $v;         // 2 (1+1)
    

    But there is no guarantee that the subexpressions are evaluated in a specified order. The documentation page of the PHP operators states (the emphasis is mine):

    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.

    Only by chance the values computed by PHP for the other expressions match the values you assumed. Their values might be different when the code is executed using a different version of the PHP interpreter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应