zoukankan      html  css  js  c++  java
  • PHP中逻辑运算符and/or与||/&&的一个坑

    我原来以为PHP中的and和&&是一样的, 只是写法上为了可读性和美观, 事实上我错了. 这里面深藏了一个坑!

    看以下代码:

    1. $bA = true;
    2. $bB = false;
    3. $b1 = $bA and $bB;
    4. $b2 = $bA && $bB;
    5. var_dump($b1); // $b1 = true
    6. var_dump($b2); // $b2 = false
    7. $bA = false;
    8. $bB = true;
    9. $b3 = $bA or $bB;
    10. $b4 = $bA || $bB;
    11. var_dump($b3); // $b3 = false
    12. var_dump($b4); // $b4 = true
    复制

    奇怪吧, and/&&和or/||出来的结果竟然不一样的. 问题出在哪里呢?
    我们再看一段代码!

    1. $bA = true;
    2. $bB = false;
    3. var_dump($bA and $bB); // false
    4. var_dump($bA && $bB); // false
    5. $bA = false;
    6. $bB = true;
    7. var_dump($bA or $bB); // true
    8. var_dump($bA || $bB); // true
    复制

    更奇怪, 这时怎么是对的. 所以问题可能出现在=上, 一番google和文档,终于找到了答案!

    运算符优先级

    通过这个表, 我们可以看到 and/&&or/|| 这两组运算符的优先级竟然是不一样的. andor的优先级是低于=的, 所以上面的代码就好理解了, 就是先做赋值然后再做了一个andor的逻辑运算, 这个运算的结果并没有存下来. 所以最后出来让我们匪夷所思的结果.

    The following table lists the operators in order of precedence, with the highest-precedence ones at the top. Operators on the same line have equal precedence, in which case associativity decides grouping.

    下表列出了运算的优先级顺序, 越靠上的越高, 同一行的优先级相同. 相同优级的使用结合性进行分组处理.

    结合性运算符额外信息
    无结合性 clone new 克隆和new
    [ 数组
    ** 算术
    ++ — ~ (int) (float) (string) (array) (object) (bool) @ 类型和自增/自减
    无结合性 instanceof 类型
    ! 逻辑运算
    * / % 算术
    + – . 算术和字符串
    << >> 按位运算
    无结合性 < <= > >= 比较运算
    无结合性 == != === !== <> 比较运算
    & 按位运算和引用
    ^ 按位运算
    | 按位运算  
    && 逻辑运算
    | | 逻辑运算  
    ?: 三元条件选择
    = += -= *= /= .= %= &= = ^= <<= >>= => | 赋值
    and 逻辑运算
    xor 逻辑运算
    or 逻辑运算
    , 很多使用

    总结

    慎重使用and, orxor的逻辑运算符, 避免和赋值号以及&&||一起用, 以免发生不必要的逻辑错误.

  • 相关阅读:
    float浮点型底层存储原理
    PermissionError: WinError
    django数据库设置sql_mode
    Git 之 git diff
    以太网数据格式与封装解封
    MYSQL进阶
    MYSQL基础
    Python连接MySQL数据库之pymysql模块使用
    Python装饰器进阶
    BootStrap框架
  • 原文地址:https://www.cnblogs.com/ZDPPU/p/5823895.html
Copyright © 2011-2022 走看看