PHP - What does "Operator precedence and associativity do not specify an order of evaluation" mean? -
i reading operator precedence section of php manual. confused (or say, don't understand following sentences quite much):
operator precedence , associativity determine how expressions grouped, not specify order of evaluation. php not (in general case) specify in order expression evaluated , code assumes specific order of evaluation should avoided, because behavior can change between versions of php or depending on surrounding code.
it gives 2 examples illustrate undefined order of evaluation.
<?php $a = 1; echo $a + $a++; // may print either 2 or 3 >? from understand, $a evaluats 1 first because associativity of addition operator left. 1 added $a++, evaluates 1. so, result should 2. why comment in documentation "may print either 2 or 3"?
the second example is:
<? $i = 1; $array[$i] = $i++; // may set either index 1 or 2 ?> similarly, $i++ evaluates 1 first because associativity of assignment operator right. value of 1 should set index 2 of array. why comment "may set either index 1 or 2"?
the explanation can think of order of code in 2 examples above can executed opposite of reasoned.
any thoughts me unravel confusion appreciated.
just because operator left-associative, doesn't mean parameters evaluated left-to-right. in
$a + $a++ it can evaluate $a first or $a++ first. in first case, result 1 + 1 = 2; in second case result 2 + 1 = 3.
associativity specifies how multiple expressions grouped when they're combined. instance, if have
1 - 2 + 3 left-associativity specifies interpreted as
(1 - 2) + 3 = 2 rather than
1 - (2 + 3) = -4 but if expression had sub-expressions side effects, still evaluate them right-to-left (or in mixed order).
Comments
Post a Comment