【问题标题】:Why are FALSE, string '0', number 0 and NULL all equal(==) between each other except null and string 0?为什么除了 null 和字符串 0 之外,FALSE、字符串 '0'、数字 0 和 NULL 彼此之间都相等(==)?
【发布时间】:2019-07-19 13:58:28
【问题描述】:

我在 php 中尝试使用空值,但我无法真正解决这个比较问题。我这样定义变量:

$a = 0;
$b = '0';
$c = false;
$d = null;

当我使用等价运算符 (==) 时,它们都是相等的,除了变量 $b 和 $d。有人可以解释一下为什么吗?我阅读了有关类型杂耍和类型转换的文档,但我仍然不明白为什么。 False 和 '0' 相等,false 和 null 相等,但 null 和 '0' 不相等。里面没有逻辑。

【问题讨论】:

  • php.net/manual/en/types.comparisons.php - Before utilizing these tables, it's important to understand types and their meanings. For example, "42" is a string while 42 is an integer. FALSE is a boolean while "false" is a string.
  • 保证安全的最好方法是使用严格比较===== 会导致很多问题,让调试变得困难。
  • 为什么$b == null后面没有逻辑导致false$b 不是 null,因为它包含一个字符串,因此不是 null

标签: php comparison-operators


【解决方案1】:

我找到了答案。在比较 null 和字符串时,PHP 将 NULL 转换为空字符串。所以 "" != "0"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-03
    • 2013-09-27
    • 2014-12-03
    相关资源
    最近更新 更多