dqrq93879 2012-07-22 16:02
浏览 48
已采纳

使用PHP相同的比较运算符和原始类型确实有意义吗?

Can't get the point of === and !== with primitive types:

$a === $b TRUE if $a is equal to $b, and they are of the same type.
$a !== $b TRUE if $a is not equal to $b, or they are not of the same type.

The assuming that $request->getMethod() returns GET or POST (as string) and that $form->isValid() returns a boolean true or false, the following code:

if('POST' === $request->getMethod() || (false === $form->isValid())) :
endif;

Does make any sense in respect of this shorter one:

if('POST' == $request->getMethod() || !$form->isValid()) :
endif;
  • 写回答

4条回答 默认 最新

  • dongpang1232 2012-07-22 16:13
    关注

    You have truty and falsy values in PHP. For instance, 0, '', array() are falsy values. If you use == it will match those values with the truty/falsy values:

    var_dump(true == 'hello'); // true because a not empty string is a truty value
    var_dump(false == 0); // true
    

    === will match not only the value but the type also:

    var_dump(true === 'hello'); // false, true is a boolean and 'hello' a string
    var_dump(false === 0); // false, false is a boolean and 0 is a string
    

    This will become a problem when a function can return 0 or false, strpos for example.


    There are also other factors with the ==. It will type cast values to a int if you compare 2 different types:

    var_dump("123abc" == 123); // true, because '123abc' becomes `123`
    

    This will be problematic if you compare a password: http://phpsadness.com/sad/47

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算