2017-02-27 81 views
1

這是我(直覺)的理解,在PHP中對整數類型的變量使用加法賦值運算符+=會產生加法的結果,同時增加左邊的操作數同時右側操作數的值。加法賦值不會在條件內賦值

這種理解似乎是錯誤的,因此我的問題。考慮下面的代碼片段:

$itr = 10; 
$incr = 10; 

if ($itr += $incr > 10) { // evaluates as true... 
    echo $itr; // but value of $itr remains unchanged 
} 

爲什麼它輸出10而不是20?

同樣的情況,採用三段式:

echo ($itr += $incr > 10) ? $itr : 'neverhere'; // prints 10 
// Note: I know that parentheses aren't really necessary here, it's just a personal practice. 

這是怎麼回事?


編輯:好,我發現,周圍用括號表達式$itr += $incr固定明顯的問題。儘管如此,爲什麼會非常酷的一個適當的解釋。我提前感謝。

+1

http://php.net/manual/en/language.operators.precedence.php –

回答

1

Operator precedence:首先評估>並導致false。當將其轉換爲一個整數以加上您的值時,false將轉換爲0

所以:

$itr += $incr > 10 

變爲:

$itr += ($incr > 10) 
$itr += (false) 
$itr += 0 
0

在if語句,你只評估$ ITR由$增量遞增的可能性,但你不能有效地指導了PHP做那。所以它永遠不會存儲新值。