PHP - 检查返回假;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6231650/
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-25 23:42:55  来源:igfitidea点击:

PHP - Checking for return false;

php

提问by lethalMango

Just a quick question - and I'm sure really basic!

只是一个简单的问题 - 我敢肯定真的很基本!

I have the following code:

我有以下代码:

function checkThings($foo, $bar) {
    ...
    if ($valid) {
        return $results;
    } else {
        return false;
    }
}

On the other end of this I am currently doing

另一方面,我目前正在做

$check = checkThings($foo, $bar);
if ($check === false) {
    echo "Error";
} else {
    echo $check;
}

Is writing the following the same?

下面的写法一样吗?

$check = checkThings($foo, $bar);
if (!$check) {
    echo "Error";
} else {
    echo $check;
}

Which method is the preferred method if both are correct?

如果两者都正确,哪种方法是首选方法?

Thanks :)

谢谢 :)

回答by Chris Baker

The triple-equal operator is type-sensitive. So when you check:

三重等号运算符是类型敏感的。所以当你检查:

if ($check === false)

... it will only be true if $checkis the boolean value "false". Wheras

...只有当$check布尔值是“false”时才会为真。惠拉斯

if ($check == false)

... is not checking specifically for boolean false, but a "falsey" value. False, in PHP, equals zero, null is "falsey", as is an empty string ("" == false == null, but "" !== false !== null). So:

...不是专门检查布尔假,而是“假”值。False,在 PHP 中,等于 0,null 是“falsey”,空字符串 ( "" == false == null, but "" !== false !== null) 也是如此。所以:

$check = 0;
if ($check == false)

... evaluates to true.

... 评估为真。

The !prefix operator is equivalent to ==. So when zero needs to be a discrete value from boolean false, the !and ==operators are not sufficient.

!前缀运算符相当于==。因此,当零需要是布尔 false 的离散值时,!==运算符是不够的。

Check out the docs for comparison operators here: http://php.net/manual/en/language.operators.comparison.php

在此处查看比较运算符的文档:http: //php.net/manual/en/language.operators.comparison.php

It is best practice to make your conditional checks as specific as possible. This is not only to avoid potential oversights in your logic, but also to make the code more maintainable for future developers. Imagine encountering a line of code like this:

最佳做法是使您的条件检查尽可能具体。这不仅是为了避免您的逻辑中的潜在疏忽,而且是为了使代码对未来的开发人员更易于维护。想象一下,遇到这样一行代码:

if (check_something($variable)) {
  // do stuff
}

I can assume the check_somethingfunction is returning a boolean value true. But, unless I go dig up the check_somethingfunction, it couldalso be returning an non-empty string, a number... who knows! Much more clear to do this:

我可以假设该check_something函数返回一个布尔值 true。但是,除非我去挖开check_something功能,它可能还可以返回一个非空字符串,数字...谁知道!更清楚地做到这一点:

if (check_something($variable) === true) {
  // do stuff
}

Now, just by looking, I know that the check_somethingfunction is expectedto return a true value. I might not know what the function does, but at least it is exactly clear what it returns. Another common example you see EVERYWHERE:

现在,通过查看,我知道该check_something函数应该返回一个真值。我可能不知道该函数的作用,但至少它返回的内容非常清楚。另一个常见的例子:

if (!$_GET['value']) {
  // do something
}

This is a pet peeve. A conditional statement should always be comparing things clearly. So, you'd want to do:

这是一个宠物的烦恼。条件语句应该始终清楚地比较事物。所以,你想做:

if (array_key_exists('value', $_GET) !== false && $_GET['value'] === '1') {
  // do something
}

Now, you can tell that I am not only checking to see if the query string parameter exists, but also whether it is equal to a specific value.

现在,您可以看出我不仅要检查查询字符串参数是否存在,还要检查它是否等于特定值。

In summary, the single !prefix operator and the ==operator are rarely useful and always ambiguous. You're best served by writing your code in a way that documents itself, or is translatable into human language to express the logic at play. A direct comparison using either !==or ===, where appropriate, is a good habit, good practice, and the least likely to produce unexpected results in your code.

总之,单!前缀运算符和==运算符很少有用并且总是模棱两可。您最好以一种记录自身的方式编写代码,或者可以翻译成人类语言来表达正在发挥作用的逻辑。在适当的情况下使用!==或 进行直接比较===是一个好习惯、好习惯,并且最不可能在您的代码中产生意外结果。

回答by David Chan

=== false checks type, (!$check) evaluates the value and will fail for values returned such as null, '' (empty string) and zero(0)

=== false 检查类型, (!$check) 评估该值,对于返回的值将失败,例如 null、''(空字符串)和 zero(0)

=== is most correct

=== 最正确

回答by Jim W.

They are similar, but not exactly the same. The !$checkis a loose checker, meaning 0and nullwould evaluate to true as well. The ===is a strict checker, meaning it must be false.

它们很相似,但并不完全相同。这!$check是一个松散的检查器,意思是0并且null也会评估为真。The===是一个严格的检查器,这意味着它必须是false

For a more indepth explanation: PHP Types Comparisons

更深入的解释:PHP 类型比较

回答by Ben Roux

== does a value comparison where === does a bitwise.

== 进行值比较,其中 === 进行按位比较。

// will return true only when $value = false
if( $value === false )

// will return true when $value = 0, $value = "", $value = null, etc
if( $value == false )
if( !$value )

回答by MarkD

I would prefer your second method, but put the positive check first (if($check) instead).

我更喜欢你的第二种方法,但首先进行肯定的检查(if($check) 代替)。

回答by Ernesto Allely

There is a case where the use of the single !prefix operator would not involve any risk and it is when the type of the expression to evaluate is always a boolean.

!某些情况下,使用单个前缀运算符不会带来任何风险,并且要评估的表达式类型始终为布尔值。

For example, the expression below

例如下面的表达式

if (!is_array($var)) {

will always behave similarly to

将始终表现得类似于

if (is_array($var) === false) {

This is because the function is_arrayalways returns a bool as result.

这是因为函数is_array总是返回一个 bool 作为结果。

is_array ( mixed $var ) : bool

Some people may find easier to read the first expression with the single !prefix operator. The only think to have in mind is that when used with expressions where the returned type is mixed we may have unexpected results as other comments already pointed.

有些人可能会发现使用单个!前缀运算符更容易阅读第一个表达式。唯一要记住的是,当与返回类型混合的表达式一起使用时,我们可能会得到意想不到的结果,正如其他评论已经指出的那样。

回答by BlackCoder

If you are trying to check for multiple conditions, you can do this:

如果您尝试检查多个条件,您可以这样做:

function checkThings($foo, $bar)
{
    else if ($valid === false)
    {
        return false;
    }
    else if ($valid === 1)
    {
        return 1;
    }
    else if ($valid === 2)
    {
        return 2;
    }
    else if ($valid === 3)
    {
        return 3;
    }
}

But you must strictly check the return of the function with "===" when you are attempting to check which value is returned and what piece of code ran.

但是,当您尝试检查返回的是哪个值以及运行了哪一段代码时,您必须使用“===”严格检查函数的返回。