# 运算符 * * * * * Table of Contents 1. 运算符优先级 2. 算术运算符 3. 赋值运算符 4. 位运算符 5. 比较运算符 6. 错误控制运算符 7. 执行运算符 8. 递增/递减运算符 9. 逻辑运算符 10. 字符串运算符 11. 数组运算符 12. 类型运算符 > 运算符是可以通过给出的一或多个值(用编程行话来说,表达式)来产生另一个值(因而整个结构成为一个表达式)的东西。 * * * * * **运算符优先级** | 无 | clone new | clone 和 new | | --- | --- | --- | | 左 | [ | array() | | 右 | ++ -- ~ (int) (float) (string) (array) (object) (bool) @ | 类型和递增/递减 | | 无 | instanceof | 类型 | | 右 | ! | 逻辑运算符 | | 左 | * / % | 算术运算符 | | 左 | + - . | 算术运算符和字符串运算符 | | 左 | << >> | 位运算符 | | 无 | == != === !== <> | 比较运算符 | | 左 | & | 位运算符和引用 | | 左 | ^ | 位运算符 | | 左 | \| | 位运算符 | | 左 | && | 逻辑运算符 | | 左 | \|\| | 逻辑运算符 | | 左 | ? : | 三元运算符 | | 右 | = += -= *= /= .= %= &= |= ^= <<= >>= => | 赋值运算符 | | 左 | and | 逻辑运算符 | | 左 | xor | 逻辑运算符 | | 左 | or | 逻辑运算符 | | 左 | , | 多处用到 | * * * * * **算术运算符** ~~~ echo ( 5 % 3 ). "\n" ; // prints 2 echo ( 5 % - 3 ). "\n" ; // prints 2 echo (- 5 % 3 ). "\n" ; // prints -2 echo (- 5 % - 3 ). "\n" ; // prints -2 ~~~ **赋值运算符** ~~~ $a = ( $b = 4 ) + 5 ; // $a 现在成了 9,而 $b 成了 4。 ~~~ **位运算符** ~~~ echo 12 ^ 9 ; // Outputs '5' echo "12" ^ "9" ; // Outputs the Backspace character (ascii 8) // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8 echo "hallo" ^ "hello" ; // Outputs the ascii values #0 #4 #0 #0 #0 // 'a' ^ 'e' = #4 echo 2 ^ "3" ; // Outputs 1 // 2 ^ ((int)"3") == 1 echo "2" ^ 3 ; // Outputs 1 // ((int)"2") ^ 3 == 1 ~~~ **比较运算符** ~~~ var_dump ( 0 == "a" ); // 0 == 0 -> true var_dump ( "1" == "01" ); // 1 == 1 -> true var_dump ( "10" == "1e1" ); // 10 == 10 -> true var_dump ( 100 == "1e2" ); // 100 == 100 -> true switch ( "a" ) { case 0 : echo "0" ; break; case "a" : // never reached because "a" is already matched with 0 echo "a" ; break; } ~~~ **错误控制运算符** ~~~ /* Intentional file error */ $my_file = @ file ( 'non_existent_file' ) or die ( "Failed opening file: error was ' $php_errormsg '" ); ~~~ **执行运算符** ~~~ $output = ` ls -al `; echo "<pre> $output </pre>" ; ~~~ **递增/递减运算符** **逻辑运算符** ~~~ $a = ( false && foo ()); $b = ( true || foo ()); $c = ( false and foo ()); $d = ( true or foo ()); ~~~ **字符串运算符** ~~~ $a = "Hello " ; $b = $a . "World!" ; // now $b contains "Hello World!" $a = "Hello " ; $a .= "World!" ; // now $a contains "Hello World!" ~~~ **数组运算符** ~~~ $a = array( "a" => "apple" , "b" => "banana" ); $b = array( "a" => "pear" , "b" => "strawberry" , "c" => "cherry" ); $c = $a + $b ; // Union of $a and $b echo "Union of \$a and \$b: \n" ; var_dump ( $c ); $c = $b + $a ; // Union of $b and $a echo "Union of \$b and \$a: \n" ; var_dump ( $c ); ~~~ **类型运算符** ~~~ class MyClass { } class NotMyClass { } $a = new MyClass ; var_dump ( $a instanceof MyClass ); var_dump ( $a instanceof NotMyClass ); ~~~