本文目錄一覽:
php中的運算符優先級是什麼樣的
下表按照優先級從高到低列出了運算符。同一行中的運算符具有相同優先級,此時它們的結合方向決定求值順序。
運算符優先級
結合方向
運算符
附加信息
無
clone new
clone 和 new
左
[
array()
右
**
算術運算符
右
++
—
~
(int)
(float)
(string)
(array)
(object)
(bool)
@
類型和遞增/遞減
無
instanceof
類型
右
!
邏輯運算符
左
*
/
%
算術運算符
左
+
–
.
算術運算符和字符串運算符
左
位運算符
無
=
=
比較運算符
無
==
!=
===
!==
=
比較運算符
左
位運算符和引用
左
^
位運算符
左
|
位運算符
左
邏輯運算符
左
||
邏輯運算符
左
??
比較運算符
左
? :
ternary
right
=
+=
-=
*=
**=
/=
.=
%=
=
|=
^=
=
=
賦值運算符
左
and
邏輯運算符
左
xor
邏輯運算符
左
or
邏輯運算符
Example #1 結合方向
?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 determine how expressions
are grouped, they do not specify an order of evaluation. PHP does not
(in the general case) specify in which order an expression is evaluated
and code that assumes a specific order of evaluation should be avoided,
because the behavior can change between versions of PHP or depending 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
?
Note:
儘管 = 比其它大多數的運算符的優先級低,PHP
仍舊允許類似如下的表達式:if (!$a = foo()),在此例中
foo() 的返回值被賦給了 $a。
php邏輯運算符和括號哪個優先級高啊
括號中的優先級更高,括號中運算結束後才會執行邏輯運算
如: 1 == (2-1)
關於php運算符優先級問題
下表按照優先級從高到低列出了運算符。同一行中的運算符具有相同優先級,此時它們的結合方向決定求值順序。
運算符優先級
結合方向
運算符
附加信息
無 clone new clone 和 new
左 [ array()
右 ++ — ~ (int) (float) (string) (array) (object) (bool) @ 類型和遞增/遞減
無 instanceof 類型
右 ! 邏輯運算符
左 * / % 算術運算符
左 + – . 算術運算符和字符串運算符
左 位運算符
無 == != === !== 比較運算符
左 位運算符和引用
左 ^ 位運算符
左 | 位運算符
左 邏輯運算符
左 || 邏輯運算符
左 ? : 三元運算符
右 = += -= *= /= .= %= = |= ^= = = = 賦值運算符
左 and 邏輯運算符
左 xor 邏輯運算符
左 or 邏輯運算符
左 , 多處用到
對具有相同優先級的運算符,左結合方向意味着將從左向右求值,右結合方向則反之。對於無結合方向具有相同優先級的運算符,該運算符有可能無法與其自身結合。
原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/127396.html