PHP中$a++与++$a的自增自减规则解析及复杂表达式计算结果22的成因咨询
Hey there! Let's clear up how ++$a (prefix increment) and $a++ (postfix increment) work in PHP, then walk through your expression step by step to figure out where the result comes from.
Basic Rules
First, let's lock down the core behavior:
- Postfix increment/decrement (
$a++,$a--): Returns the current value of the variable first, then increments/decrements the variable by 1. - Prefix increment/decrement (
++$a,--$a): Increments/decrements the variable by 1 first, then returns the updated value. - Unary negative (
-$a) simply returns the negative of the variable's current value, with lower precedence than postfix increment/decrement but equal to prefix increment/decrement (right-associative).
Step-by-Step Breakdown of Your Expression
You defined $a = 5, then calculated:
$a++ + $a-- + -$a + ++$a + $a++ + ++$a - $a-- + $a
Let's compute each term left to right, tracking $a's value and the cumulative result at every step:
First term:
$a++- Postfix increment: Return current value
5, then$abecomes6. - Cumulative result:
5
- Postfix increment: Return current value
Second term:
$a--- Postfix decrement: Return current value
6, then$abecomes5. - Cumulative result:
5 + 6 = 11
- Postfix decrement: Return current value
Third term:
-$a- Unary negative: Current
$ais5, so return-5. - Cumulative result:
11 + (-5) = 6
- Unary negative: Current
Fourth term:
++$a- Prefix increment: First set
$afrom5to6, then return6. - Cumulative result:
6 + 6 = 12
- Prefix increment: First set
Fifth term:
$a++- Postfix increment: Return current value
6, then$abecomes7. - Cumulative result:
12 + 6 = 18
- Postfix increment: Return current value
Sixth term:
++$a- Prefix increment: First set
$afrom7to8, then return8. - Cumulative result:
18 + 8 = 26
- Prefix increment: First set
Seventh term:
- $a--- Postfix decrement has higher precedence than unary negative: First return current
$avalue8, then$abecomes7, then apply the negative sign to get-8. - Cumulative result:
26 + (-8) = 18
- Postfix decrement has higher precedence than unary negative: First return current
Eighth term:
$a- Current
$ais7, return7. - Final result:
18 + 7 = 25
- Current
Wait a minute—this gives us 25, but you mentioned getting 22 when running the code. A few possible reasons for this discrepancy:
- Did you possibly mistype the expression (e.g., using
--$ainstead of- $a, or missing a term)? - Was the initial value of
$anot5? - Could there be other code modifying
$abefore this expression runs?
If you double-check the code with the exact expression you shared, it should output 25 in both PHP 7 and PHP 8.
内容的提问来源于stack exchange,提问作者Phạm Văn Hậu

