PHP 中的 Null 与 False 与 0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/137487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:37:40  来源:igfitidea点击:

Null vs. False vs. 0 in PHP

phpnull

提问by stalepretzel

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

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

回答by e-satis

It's language specific, but in PHP :

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

Nullmeans "nothing". The var has not been initialized.

Null意思是“没有”。var 尚未初始化。

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

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

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

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

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.

现在,棘手的是,在像 PHP 这样的动态语言中,它们都在布尔上下文中具有一个值,(在 PHP 中)是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.

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

So why are they useful ?

那么它们为什么有用呢?

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 !

嗯,看strrpos()功能。如果没有找到任何东西,则返回 False,但如果在字符串的开头找到了一些东西,则返回 0!

<?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:

当然,如果你处理状态:

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 ;-)).

您想在DebugMode = False(设置为关闭)、DebugMode = True(设置为打开)和DebugMode = Null(根本不设置,将导致调试困难;-))之间有所不同。

回答by gcb

nullis null. falseis false. Sad but true.

nullnullfalsefalse。悲伤但真实。

there's not much consistency in PHP. the developers TRYto make null means "unkown" or "non-existent". but often False will serve as 'non-existent' (e.g. strrpos('fail', 'search') will return false, and not null)

PHP 没有太多的一致性。开发人员尝试使 null 表示“未知”或“不存在”。但通常 False 将作为“不存在”(例如 strrpos('fail', 'search') 将返回 false,而不是 null)

you will often see null being used when they are already using false for something. e.g. filter_input(). They return false if the variable fails the filter. and null if the variable does not exists (does not existing means it also failed the filter? so why even return null?!?)

当他们已经为某事使用 false 时,您经常会看到使用 null 。例如 filter_input()。如果变量未通过过滤器,它们将返回 false。如果变量不存在,则为 null(不存在意味着它也未能通过过滤器?那为什么还要返回 null?!?)

php has the convenience of returning data in the functions. and ofter the developers cram in all kind of failure status instead of the data.

php具有在函数中返回数据的便利性。并且开发人员经常会塞进各种故障状态而不是数据。

And There's no sane way in PHP to detect data (int, str, etc) from failure (false, null)

并且 PHP 中没有理智的方法来从失败(false、null)中检测数据(int、str 等)

you pretty much have to always test for ===null or ===false, depending on the function. or for both, in cases such as filter_input()/filter_var()

您几乎必须始终测试 ===null 或 ===false,具体取决于函数。或两者兼而有之,例如 filter_input()/filter_var()

and here's some fun with type juggling. not even including arrays and objects.

这里有一些打字杂耍的乐趣。甚至不包括数组和对象。

var_dump( 0<0 );        #bool(false)
var_dump( 1<0 );        #bool(false)
var_dump( -1<0 );       #bool(true)
var_dump( false<0 );    #bool(false)
var_dump( null<0 );     #bool(false)
var_dump( ''<0 );       #bool(false)
var_dump( 'a'<0 );      #bool(false)
echo "\n";
var_dump( !0 );        #bool(true)
var_dump( !1 );        #bool(false)
var_dump( !-1 );       #bool(false)
var_dump( !false );    #bool(true)
var_dump( !null );     #bool(true)
var_dump( !'' );       #bool(true)
var_dump( !'a' );      #bool(false)
echo "\n";
var_dump( false == 0 );        #bool(true)
var_dump( false == 1 );        #bool(false)
var_dump( false == -1 );       #bool(false)
var_dump( false == false );    #bool(true)
var_dump( false == null );     #bool(true)
var_dump( false == '' );       #bool(true)
var_dump( false == 'a' );      #bool(false)
echo "\n";
var_dump( null == 0 );        #bool(true)
var_dump( null == 1 );        #bool(false)
var_dump( null == -1 );       #bool(false)
var_dump( null == false );    #bool(true)
var_dump( null == null );     #bool(true)
var_dump( null == '' );       #bool(true)
var_dump( null == 'a' );      #bool(false)
echo "\n";
$a=0; var_dump( empty($a) );        #bool(true)
$a=1; var_dump( empty($a) );        #bool(false)
$a=-1; var_dump( empty($a) );       #bool(false)
$a=false; var_dump( empty($a) );    #bool(true)
$a=null; var_dump( empty($a) );     #bool(true)
$a=''; var_dump( empty($a) );       #bool(true)
$a='a'; var_dump( empty($a));      # bool(false)
echo "\n"; #new block suggested by @thehpi
var_dump( null < -1 ); #bool(true)
var_dump( null < 0 ); #bool(false)
var_dump( null < 1 ); #bool(true)
var_dump( -1 > true ); #bool(false)
var_dump( 0 > true ); #bool(false)
var_dump( 1 > true ); #bool(true)
var_dump( -1 > false ); #bool(true)
var_dump( 0 > false ); #bool(false)
var_dump( 1 > true ); #bool(true)

回答by KristCont

Below is an example:

下面是一个例子:

            Comparisons of $x with PHP functions

Expression          gettype()   empty()     is_null()   isset() boolean : if($x)
$x = "";            string      TRUE        FALSE       TRUE    FALSE
$x = null;          NULL        TRUE        TRUE        FALSE   FALSE
var $x;             NULL        TRUE        TRUE        FALSE   FALSE
$x is undefined     NULL        TRUE        TRUE        FALSE   FALSE
$x = array();       array       TRUE        FALSE       TRUE    FALSE
$x = false;         boolean     TRUE        FALSE       TRUE    FALSE
$x = true;          boolean     FALSE       FALSE       TRUE    TRUE
$x = 1;             integer     FALSE       FALSE       TRUE    TRUE
$x = 42;            integer     FALSE       FALSE       TRUE    TRUE
$x = 0;             integer     TRUE        FALSE       TRUE    FALSE
$x = -1;            integer     FALSE       FALSE       TRUE    TRUE
$x = "1";           string      FALSE       FALSE       TRUE    TRUE
$x = "0";           string      TRUE        FALSE       TRUE    FALSE
$x = "-1";          string      FALSE       FALSE       TRUE    TRUE
$x = "php";         string      FALSE       FALSE       TRUE    TRUE
$x = "true";        string      FALSE       FALSE       TRUE    TRUE
$x = "false";       string      FALSE       FALSE       TRUE    TRUE

Please see this for more reference of type comparisonsin PHP. It should give you a clear understanding.

有关PHP中类型比较的更多参考,请参阅此处。它应该让你有一个清晰的理解。

回答by inkredibl

In PHP you can use === and !== operators to check not only if the values are equal but also if their types match. So for example: 0 == falseis true, but 0 === falseis false. The same goes for !=versus !==. Also in case you compare nullto the other two using the mentioned operators, expect similar results.

在 PHP 中,您可以使用 === 和 !== 运算符来检查值是否相等,还可以检查它们的类型是否匹配。例如:0 == falsetrue,但是0 === falsefalse。对于!=vs 也是如此!==。此外,如果您null使用上述运算符与其他两个进行比较,请期待类似的结果。

Now in PHP this quality of values is usually used when returning a value which sometimes can be 0(zero), but sometimes it might be that the function failed. In such cases in PHP you return falseand you have to check for these cases using the identity operator ===. For example if you are searching for a position of one string inside the other and you're using strpos(), this function will return the numeric position which can be 0 if the string is found at the very beginning, but if the string is not found at all, then strpos()will return falseand you have to take this into account when dealing with the result.

现在在 PHP 中,当返回有时可以是0(零)的值时,通常会使用这种值的质量,但有时可能是函数失败了。在这种情况下,在 PHP 中您返回false并且您必须使用身份运算符检查这些情况===。例如,如果您正在搜索一个字符串在另一个字符串中的位置,并且您正在使用strpos(),则此函数将返回数字位置,如果在最开始找到该字符串,则该位置可以为 0,但如果在此位置找不到该字符串all,然后strpos()将返回false,您在处理结果时必须考虑到这一点。

If you will use the same technique in your functions, anybody familiar with the standard PHP library will understand what is going on and how to check if the returned value is what is wanted or did some error occur while processing. The same actually goes for function params, you can process them differently depending on if they are arrays or strings or what not, and this technique is used throughout PHP heavily too, so everybody will get it quite easily. So I guess that's the power.

如果您将在您的函数中使用相同的技术,任何熟悉标准 PHP 库的人都会了解正在发生的事情以及如何检查返回值是否符合要求或在处理过程中是否发生了某些错误。函数参数实际上也是如此,你可以根据它们是数组还是字符串或不是什么来对它们进行不同的处理,而且这种技术在整个 PHP 中也大量使用,所以每个人都会很容易地得到它。所以我想这就是力量。

回答by Orion Adrian

False, Null, Nothing, 0, Undefined, etc., etc.

False、Null、Nothing、0、Undefined等,等等。

Each of these has specific meanings that correlate with actual concepts. Sometimes multiple meanings are overloaded into a single keyword or value.

这些中的每一个都有与实际概念相关的特定含义。有时多个含义被重载为单个关键字或值。

In Cand C++, NULL, Falseand 0are overloaded to the same value. In C#they're 3 distinct concepts.

CC++ 中NULL,False0被重载为相同的值。在C# 中,它们是 3 个不同的概念。

nullor NULLusually indicates a lack of value, but usually doesn't specify why. 0indicates the natural number zero and has type-equivalence to 1, 2, 3,etc. and in languages that support separate concepts of NULLshould be treated only a number.

nullNULL通常表示缺乏价值,但通常不说明原因。 0表示自然数零,并且与1、2、3等具有类型等价性并且在支持 的单独概念的语言中NULL应该仅被视为一个数字。

Falseindicates non-truth. And it used in binary values. It doesn't mean unset, nor does it mean 0. It simply indicates one of two binary values.

表示不真实。它用于二进制值。这并不意味着未设置,也不意味着0. 它只是表示两个二进制值之一。

Nothing can indicate that the value is specifically set to be nothing which indicates the same thing as null, but with intent.

Nothing 可以表示该值专门设置为 nothing 表示与 null 相同的事物,但有意图。

Undefined in some languages indicates that the value has yet to be set because no code has specified an actual value.

在某些语言中未定义表示尚未设置该值,因为没有代码指定实际值。

回答by madesignUK

I have just wasted 1/2 a day trying to get either a 0, null, falseto return from strops!

我刚刚浪费了 1/2 天试图从0, null,false中返回strops

Here's all I was trying to do, before I found that the logic wasn't flowing in the right direction, seeming that there was a blackhole in php coding:

这就是我试图做的所有事情,在我发现逻辑没有朝着正确的方向流动之前,似乎在 php 编码中有一个黑洞:

Concept take a domain name hosted on a server, and make sure it's not root level, OK several different ways to do this, but I chose different due to other php functions/ constructs I have done.

概念采用托管在服务器上的域名,并确保它不是根级别,可以通过几种不同的方法来做到这一点,但由于我已经完成的其他 php 函数/构造,我选择了不同的方法。

Anyway here was the basis of the cosing:

无论如何,这是cosing的基础:

if (strpos($_SERVER ['SERVER_NAME'], dirBaseNAME ()) 
{ 
    do this 
} else {
    or that
}

{
echo strpos(mydomain.co.uk, mydomain);  

if ( strpos(mydomain, xmas) == null ) 
    {
        echo "\n1 is null"; 
    }

if ( (strpos(mydomain.co.uk, mydomain)) == 0 ) 
    {
        echo "\n2 is 0"; 
    } else {
        echo "\n2 Something is WRONG"; 
    }

if ( (mydomain.co.uk, mydomain)) != 0 ) 
    {
        echo "\n3 is 0"; 
    } else {
        echo "\n3 it is not 0"; 
    }

if ( (mydomain.co.uk, mydomain)) == null ) 
    {
        echo "\n4 is null"; 
    } else {
        echo "\n4 Something is WRONG"; 
    }
}

FINALLY after reading this Topic, I found that this worked!!!

最终在阅读本主题后,我发现这有效!!!

{
if ((mydomain.co.uk, mydomain)) !== false ) 
    {
        echo "\n5 is True"; 
    } else {
        echo "\n5 is False"; 
    }
}

Thanks for this article, I now understand that even though it's Christmas, it may not be Christmas as false, as its also can be a NULLday!

感谢这篇文章,我现在明白了,即使是圣诞节,也可能不是圣诞节false,因为它也可以是NULL一天!

After wasting a day of debugging some simple code, wished I had known this before, as I would have been able to identify the problem, rather than going all over the place trying to get it to work. It didn't work, as False, NULLand 0are not all the same as True or False or NULL?

在浪费了一天调试一些简单的代码之后,希望我之前就知道这一点,因为我本来能够识别问题,而不是到处试图让它工作。它不起作用,因为FalseNULL并且0True or False or NULL?

回答by Javier Constanzo

From the PHP online documentation:

来自PHP 在线文档

To explicitly convert a value to boolean, use the (bool) or (boolean) casts.
However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
When converting to boolean, the following values are considered FALSE:

要将值显式转换为布尔值,请使用 (bool) 或 (boolean) 强制转换。
然而,在大多数情况下,强制转换是不必要的,因为如果运算符、函数或控制结构需要布尔参数,值将被自动转换。
转换为布尔值时,以下值被视为 FALSE:

  • the boolean FALSEitself
  • the integer ``0 (zero)
  • the float 0.0(zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL(including unset variables)
  • SimpleXML objects created from empty tags
    Every other value is considered TRUE(including any resource).
  • 布尔值FALSE本身
  • 整数``0(零)
  • 浮点数0.0(零)
  • 空字符串和字符串 "0"
  • 一个元素为零的数组
  • 具有零成员变量的对象(仅限 PHP 4)
  • 特殊类型NULL(包括未设置的变量)
  • 从空标签创建的 SimpleXML 对象
    会考虑所有其他值TRUE(包括任何资源)。

So, in most cases, it's the same.

所以,在大多数情况下,它是一样的。

On the other hand, the ===and the ==are not the same thing. Regularly, you just need the "equals" operator. To clarify:

另一方面,the===和 the==不是一回事。通常,您只需要“等于”运算符。澄清:

$a == $b    //Equal. TRUE if $a is equal to $b.
$a === $b   //Identical. TRUE if $a is equal to $b, and they are of the same type. 

For more information, check the "Comparison Operators" page in the PHP online docs.

有关更多信息,请查看PHP 在线文档中的“比较运算符”页面。

Hope this helps.

希望这可以帮助。

回答by dirtside

One interesting fact about NULLin PHP: If you set a var equal to NULL, it is the same as if you had called unset()on it.

NULLPHP 中的一个有趣事实:如果您将 var 设置为等于NULL,则与调用unset()它的效果相同。

NULLessentially means a variable has no value assigned to it; falseis a valid Boolean value, 0is a valid integer value, and PHP has some fairly ugly conversions between 0, "0", "", and false.

NULL本质上意味着一个变量没有赋值给它;false是一个有效的布尔值,0是一个有效的整数值,和PHP之间有一些非常丑陋的转换0"0""",和false

回答by Gavin M. Roy

In PHP it depends on if you are validating types:

在 PHP 中,这取决于您是否正在验证类型:

( 
 ( false !== 0 ) && ( false !== -1 ) && ( false == 0 ) && ( false == -1 ) &&
 ( false !== null ) && ( false == null ) 
)

Technically null is 0x00but in PHP ( null == 0x00 ) && ( null !== 0x00 ).

技术上 null0x00只是在 PHP 中( null == 0x00 ) && ( null !== 0x00 )

0is an integer value.

0是一个整数值。

回答by Chad

I think bad developers find all different uses of null/0/false in there code.

我认为糟糕的开发人员在那里的代码中发现了 null/0/false 的所有不同用途。

For example, one of the most common mistakes developers make is to return error code in the form of data with a function.

例如,开发人员最常犯的错误之一是使用函数以数据的形式返回错误代码。

// On error GetChar returns -1
int GetChar()

This is an example of a sugar interface. This is exsplained in the book "Debuging the software development proccess" and also in another book "writing correct code".

这是一个糖接口的例子。这在“调试软件开发过程”一书中以及另一本书“编写正确的代码”中都有说明。

The problem with this, is the implication or assumptions made on the char type. On some compilers the char type can be non-signed. So even though you return a -1 the compiler can return 1 instead. These kind of compiler assumptions in C++ or C are hard to spot.

这个问题是对 char 类型的暗示或假设。在某些编译器上,char 类型可以是无符号的。因此,即使您返回 -1,编译器也可以返回 1。很难发现 C++ 或 C 中的这些编译器假设。

Instead, the best way is not to mix error code with your data. So the following function.

相反,最好的方法是不要将错误代码与您的数据混合。所以下面的函数。

char GetChar()

now becomes

现在变成

// On success return 1
// on failure return 0
bool GetChar(int &char)

This means no matter how young the developer is in your development shop, he or she will never get this wrong. Though this is not talking about redudancy or dependies in code.

这意味着无论开发人员在您的开发商店中有多年轻,他或她都不会出错。虽然这不是在谈论代码中的冗余或依赖关系。

So in general, swapping bool as the first class type in the language is okay and i think joel spoke about it with his recent postcast. But try not to use mix and match bools with your data in your routines and you should be perfectly fine.

所以总的来说,将 bool 作为语言中的第一类类型是可以的,我认为 joel 在他最近的 postcast 中谈到了它。但是尽量不要在你的例程中使用混合和匹配布尔值与你的数据,你应该完全没问题。