The precedence of an operator specifies how "tightly" it binds two expressions together. For instance, in the expression 1 + 5 * 3, the answer is 16 rather than 18 as the multiplication ("*") operator includes a higher precedence compared to the addition ("+") operator. Parentheses enable you to force precedence, if necessary. For example: (1 + 5) * 3 evaluates to 18.
Source: PHP Operators
When operators have equal precedence their associativity decides the way the operators are grouped. For instance "-" is left-associative, so 1 - 2 - 3 is usually grouped as (1 - 2) - 3 and evaluates to -4. "=" however is right-associative, so $a = $b = $c is definitely grouped as $a = ($b = $c).
Operators of equal precedence that are non-associative can't be used next to one another, for instance 1 < 2 > 1 is illegal in PHP. The expression 1 <= 1 == 1 however is legal, as the == operator offers lesser precedence compared to the <= operator.
Make use of parentheses, even though not strictly necessary, could increase readability of the code by making grouping explicit instead of counting on the implicit operator precedence and associativity.
The next table lists the operators to be able of precedence, with the highest-precedence ones at the very top. Operators on a single line possess equal precedence, in which particular case associativity decides grouping.
Example #1 Associativity
<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
// ternary operator associativity differs from C/C++
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2
$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>
Operator precedence and associativity only regulate how expressions are grouped, they don't specify an order of evaluation. PHP will not (in the overall case) specify where order an expression is usually evaluated and code that assumes a particular order of evaluation ought to be avoided, as the behavior can transform between versions of PHP or based 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
?>
Example #3 +, - and . have the same precedence
<?php
$x = 4;
// this line might result in unexpected output:
echo "x minus one equals " . $x-1 . ", or so I hope\n";
// because it is evaluated like this line:
echo (("x minus one equals " . $x) - 1) . ", or so I hope\n";
// the desired precedence can be enforced by using parentheses:
echo "x minus one equals " . ($x-1) . ", or so I hope\n";
?>
Kommentarer