來源
運(yùn)算符優(yōu)先級(jí) Example #2 Undefined order of evaluation
原文
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.
Example #2 Undefined order of evaluation
<?php
$a = 1;
echo $a + $a++; // may print either 2 or 3
$i = 1;
$array[$i] = $i++; // may set either index 1 or 2
?>
翻譯
運(yùn)算符的優(yōu)先級(jí)和結(jié)合性可以用來幫我們對(duì)一個(gè)表達(dá)式進(jìn)行拆解紧憾,但不指定賦值順序稿辙。一般情況下嘱巾,PHP不指定求值表達(dá)式的順序授嘀。我們也應(yīng)該避免使用這種基于特定求值順序的代碼物咳。因?yàn)榛诓煌腜HP版本或關(guān)聯(lián)代碼,可能會(huì)有不同的產(chǎn)生不同的行為蹄皱。
再解釋
- 在 不同PHP版本在線測(cè)試工具 中览闰,可以測(cè)試得到『$a + $a++』在 5.0.5 及以下版本中結(jié)果為 2,更高版本中巷折,結(jié)果為 3 压鉴。
- 『++』的優(yōu)先級(jí)是高于『+』,這是毋庸置疑的锻拘;而根據(jù)『++』的定義油吭,$a 應(yīng)該是使用了原值,再進(jìn)行『++』操作逊拍。
- 那么上鞠,要對(duì)『$a + $a++』的結(jié)果為2或3做解釋,只有這樣:
整個(gè)表達(dá)式結(jié)果為2:第一芯丧、二個(gè)$a值均為1芍阎,得到表達(dá)式結(jié)果為2;再$a++缨恒。
整個(gè)表達(dá)式結(jié)果為3:第二個(gè)$a值為1谴咸;$a++轮听,$a值變?yōu)?;第一個(gè)$a值為2岭佳。
總結(jié)
PHP語言在設(shè)計(jì)時(shí)血巍,沒有考慮過『++』或『--』運(yùn)算符同『表達(dá)式求值』完全分離(比如說『++』在變量后的話,就在整個(gè)表達(dá)式得到值(過程中忽略自增)后珊随,再自增)述寡,不同PHP版本存在不同的實(shí)現(xiàn)策略,導(dǎo)致同一個(gè)表達(dá)式可能會(huì)有不同的值叶洞。
實(shí)際開發(fā)中鲫凶,表達(dá)式中如果使用了『++』或『--』,那么對(duì)應(yīng)的變量在該表達(dá)式中不應(yīng)該出現(xiàn)大于1次衩辟。