Home > Backend Development > PHP Tutorial > 一个php运算符优先级有关问题

一个php运算符优先级有关问题

WBOY
Release: 2016-06-13 13:20:19
Original
985 people have browsed it

一个php运算符优先级问题
先看一个运算符优先级表

Operator Precedence(运算符优先级)

引用
Associativity Operators Additional Information
non-associative clone new clone and new
left [ array()
non-associative ++ -- increment/decrement
right ~ - (int) (float) (string) (array) (object) (bool) @ types
non-associative instanceof types
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
left and logical
left xor logical
left or logical
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());
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template