$a = 0; $b = 0; if($a=3 or $b=3){ $a++; $b++; } echo $a.",".$b;
返還值為4,1
$a = 0; $b = 0; if($a=3 || $b=3){ $a++; $b++; } echo $a.",".$b;
返還值為1,1
why?
第一則中的or文法錯了嘛?
wamp環境,php5.5.12
回複內容:
$a = 0; $b = 0; if($a=3 or $b=3){ $a++; $b++; } echo $a.",".$b;
返還值為4,1
$a = 0; $b = 0; if($a=3 || $b=3){ $a++; $b++; } echo $a.",".$b;
返還值為1,1
why?
第一則中的or文法錯了嘛?
wamp環境,php5.5.12
1.首先,請查看php.net對所有運算子優先順序順序規定表:http://php.net/manual/zh/language.operators.precedence.php;
2.我們發現||大於=大於or(這裡指運算子優先順序),且=是右結合順序;
3.因此,在第二段snippet中的if條件結合順序應該是if($a=(3||($b=3)))
,因為php.net上面的連結文檔又說了'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.',翻譯一下就是說:運算子的優先順序和結合性只是決定了運算式如何分組,卻沒有指定代碼被如何解析執行。。。,所以這裡的if條件並不能完全按照運算子的優先順序和結合性來判斷代碼如何解析執行。
關注“PHP技術大全”公眾號(phpgod),拿起手機,開啟,輕鬆一掃下面的二維碼,每天成長一點,成就大神就不遠。
你以為if($a=3 || $b=3)
是if(($a=3) || ($b=3))
其實由於運算子優先順序的原因,是if($a = ( 3 || ($b = 3) ) )
然後 3 || ($b = 3)
這一句,由於短路特性($b = 3)並沒有執行,這句的傳回值是布爾類型true,返回給$a,echo出來是1,其自增值也不會改變。$b依然是0,自增成1。