Null vs.False vs.0在PHP中 [英] Null vs. False vs. 0 in PHP

查看:73
本文介绍了Null vs.False vs.0在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 表示"没有内容".变量尚未初始化.

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(设置为off),DebugMode = True(设置为on)和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 ;-)).

这篇关于Null vs.False vs.0在PHP中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆