PHP 5.6代码:
$nl = '<br/>';
$text = 'hello';
$res = $text? 'true': 'false';
echo "$text evaluates to $res $nl";
$num = 0;
$res = $num? 'true': 'false';
echo "0 evaluates to $res $nl";
$res = $text == 0? 'true': 'false';
echo "$text == $num evaluates to $res $nl";
输出:
hello evaluates to true
0 evaluates to false
hello == 0 evaluates to true
我不理解输出的最后一行。如何将true
与某些内容false
进行比较并得到true
的比较结果?
答案:我怀疑字符串和整数不都转换为布尔值。相反,字符串将转换为数字,然后与0进行比较。因为字符串不是以数字字符开头,所以它的计算结果为0(var_dump((int)'hello')
将输出int 0
)。因此,比较会返回true
,因为"hello" == 0
变为0 == 0