一個php運算子優先順序問題
先看一個運算子優先順序表
Operator Precedence(運算子優先順序)
引用
AssociativityOperatorsAdditional Information
non-associativeclone newclone and new
left[array()
non-associative++ --increment/decrement
right~ - (int) (float) (string) (array) (object) (bool) @types
non-associativeinstanceoftypes
right!logical
left* / %arithmetic
left+ - .arithmetic and string
left<< >>bitwise
non-associative< <= > >= <>comparison
non-associative== != === !==comparison
left&bitwise and references
left^bitwise
left|bitwise
left&&logical
left||logical
left?:ternary
right= += -= *= /= .= %= &= |= ^= <<= >>= =>assignment
leftandlogical
leftxorlogical
leftorlogical
left,many uses
引用
&& 優先於 = 優先於 and
但是
引用
$a = 100 && $b = 200
按照運算子優先順序規則順序應該是
引用
$a = ( ( 100 && $b ) = 200 )
但是php裡有規定,
引用
Note: Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.
所以實際效果是
引用
( $a = 100 )&& ( $b = 200 )
相當於把 && 變成了 and
另外,引用鳥哥的一個例子
引用
最後, 順便說一下, PHP對應於T_BOOLEAN_AND 還定義了 T_LOGICAL_AND(and) 和 T_LOGICAL_OR(or) , 這倆個的優先順序都低於等號, 於是就會有了, 很多PHP入門教材範例程式碼中經典的:
$result = mysql_query(*) or die(mysql_error());