PHP布尔值TRUE/FALSE是什么?

8

I can't figure this out.

If I type:

function myfunction(){
    ......
    if ...
        return TRUE;
    if ...
        return FALSE;
}

为什么我不能像这样使用它:
$result = myfunction();
if ($result == TRUE)
...
if ($result == FALSE)
...

我需要使用什么:
或者我必须使用:
$result = myfunction();
if ($result == 1)
...
if ($result == 0)
...

或者这个:
$result = myfunction();
if ($result)
...
if (!$result)
...

小备注:像这样读取的代码:if … return true; else return false;应始终重写为 return … === true; 或在类型安全的语言中,简单地重写为 return …;。 这里的if没有意义,因为我们正在测试的条件已经对应于返回值。 - Konrad Rudolph
6个回答

19

我不完全理解你的问题,但是你可以使用你提供的任何示例,但需要注意以下几点:

如果你写if (a == TRUE) (或者,由于与 true 的比较是多余的,可以直接写成if (a)),你必须明白 PHP 会将几个值视为真:1、2、987、"hello"等,它们都是“真”的值。这很少成为问题,但你应该明白它。

然而,如果函数可以返回不止 true 或者 false,那么你可能会对使用 === 感兴趣。 === 进行变量类型的比较:"a" == truetrue,但 "a" === true 则为false。


6
如果您不需要进一步使用结果变量$result,我会使用以下最短版本:
if (myfunction()) {
    // something when true
} else {
    // something else when false
}

5
你可以这样做:
$result = myfunction();
if ($result === TRUE)
...
if ($result === FALSE)
...

3

您可以使用if($result),这已经足够了,但是if($result == TRUE)有点过度。


0
if($variable) 
//something when truw
else 
//something else when false

请记住,值-1被视为TRUE,就像任何其他非零(无论是负数还是正数)数字一样。FALSE将是0,显然...

-1

请仔细检查您的gettype($result) == bool,而不是string。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接