PHP 中的 Null 与 False 与 0

2022-01-06 00:00:00 null php

有人告诉我,优秀的开发人员可以发现/利用 NullFalse0 以及所有其他好的无"之间的区别实体.
有什么区别,特别是在 PHP 中?和===有关系吗?

I am told that good developers can spot/utilize the difference between Null and False and 0 and all the other good "nothing" entities.
What is the difference, specifically in PHP? Does it have something to do with ===?

推荐答案

它是特定于语言的,但在 PHP 中:

Null 表示没有".var 尚未初始化.

It's language specific, but in PHP :

Null means "nothing". The var has not been initialized.

False 表示在布尔上下文中不为真".用于明确表明您正在处理逻辑问题.

False means "not true in a boolean context". Used to explicitly show you are dealing with logical issues.

0 是一个 int.与上面的其余部分无关,用于数学.

0 is an int. Nothing to do with the rest above, used for mathematics.

现在,棘手的是,在像 PHP 这样的动态语言中,它们在布尔上下文中都有一个值,(在 PHP 中)是 False.

Now, what is tricky, it's that in dynamic languages like PHP, all of them have a value in a boolean context, which (in PHP) is False.

如果你用 == 测试它,它正在测试布尔值,所以你会得到相等.如果你用====测试它,它会测试类型,你会得到不等式.

If you test it with ==, it's testing the boolean value, so you will get equality. If you test it with ===, it will test the type, and you will get inequality.

好吧,看看 strrpos() 函数.如果没有找到任何东西,则返回 False,如果在字符串的开头找到了一些东西,则返回 0!

Well, look at the strrpos() function. It returns False if it did not found anything, but 0 if it has found something at the beginning of the string !

<?php
// pitfall :
if (strrpos("Hello World", "Hello")) { 
    // never exectuted
}

// smart move :
if (strrpos("Hello World", "Hello") !== False) {
    // that works !
}
?>

当然,如果你处理状态:

And of course, if you deal with states:

您想区分 DebugMode = False(设置为关闭)、DebugMode = True(设置为打开)和 DebugMode = Null(根本不设置,会导致调试困难;-)).

You want to make a difference between DebugMode = False (set to off), DebugMode = True (set to on) and DebugMode = Null (not set at all, will lead to hard debugging ;-)).

相关文章