All PHP operators have a precedence, which determines when the operator is applied in an expression. Consider the following expression:

echo 4+5*6;

You could read this expression in one of two ways:
  • Add 5 to 4, then multiply the result by 6 to produce 54
  • Multiply 5 by 6, then add 4 to produce 34
In fact PHP takes the second approach, because the * (multiplication) operator has a higher precedence than the +(addition) operator. PHP first multiplies 5 by 6 to produce 30, then adds 4 to produce 34.

Here's a list of common PHP operators ordered by precedence (highest precedence first):
Operator(s)Description
++ --increment/decrement
(int) (float) (string) (array) (object) (bool)casting
!logical “not”
* / %arithmetic
+ - .arithmetic and string
< <= > >= <>comparison
== != === !==comparison
&&logical “and”
||logical “or”
= += -= *= /= .= %=assignment
andlogical “and”
xorlogical “xor”
orlogical “or”
Note:Operators on the same line in the list have the same precedence.

If you want to change the order that operators are applied, use parentheses. The following expression evaluates to 54, not 34:
( 4 + 5 ) * 6
<?php
function test()
{
    static 
$a 0;
    echo 
$a;
    
$a++;
}
test(); // output should 0
test(); // output should 1
test(); //output should 2
?>

0 comments:

Post a Comment

 
Top
Blogger Template