PHP 布尔回声输出


php bool echo output

我有一个奇怪的问题。

如果 有 函数执行此操作返回值,

public function isVipCustomer($customer_id){
        $cus_vip_id=FALSE;
        $sql="SELECT customerid FROM customers WHERE is_vip='1' 
                AND customerid='".$customer_id."' LIMIT 0,1 ";  
        $result= $this->db->query($sql);
        while($row=mysqli_fetch_assoc($result)){
            $cus_vip_id=(int)$row['customerid'];    
        }
        if($cus_vip_id!=0)
            return TRUE;
        else
            return FALSE;
    }

当我打电话时

$customer_id=13;
echo $collection->isVipCustomer($customer_id);
当它为真时,它输出

1,但当它为假时,它为空,期望输出为 0

为什么?

来自 PHP 文档:

布尔值 TRUE 将转换为字符串"1"。布尔值 FALSE 是 转换为 "(空字符串)。这允许转换回来和 在布尔值和字符串值之间。

http://www.php.net/manual/en/language.types.string.php

若要使用类型打印回返回值,请尝试改用 var_dump($myVar)

将布尔值转换为字符串时,true转换为"1"false转换为""(空字符串)。

http://php.net/manual/en/language.types.string.php#language.types.string.casting

您的期望不正确。

这就是 PHP 在将布尔值转换为字符串时所做的。
试试这个:

echo $collection->isVipCustomer($customer_id) ? 1 : 0;

或者,如果您只想输出一些用于调试目的的内容,并且想要有一个明确的 false 标志,请使用以下命令:

var_dump($collection->isVipCustomer($customer_id));

这将输出bool(true)bool(false)