PHP 类型转换混淆 [英] PHP Type-Cast Confusion

查看:30
本文介绍了PHP 类型转换混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

<?php
    $val = 0;
    $res = $val == 'true';

    var_dump($res);
?>

我总是觉得 $res 应该是 'false',因为在上面的表达式中 PHP 会尝试将 $val 类型转换为布尔类型(其中零将被转换为 false)和一个字符串(非空字符串是真的).但是如果我执行上面的代码输出将是:

I always was under impression that $res should be 'false' as in the above expression PHP would try to type cast $val to boolean type (where zero will be converted as false) and a string (non-empty string is true). But if I execute the code above output will be:

boolean true

我错过了什么吗?谢谢.

Am I missing something? Thanks.

推荐答案

在 PHP 中,所有非空、非数字字符串的计算结果为零,因此 0 == 'true' 为 TRUE,但是 0 === 'true' 是假的.字符串 true 尚未转换为布尔值,而是作为 字符串 与零进行比较.零保留为 int 值,而不是转换为布尔值.所以最终你会得到:

In PHP, all non-empty, non-numeric strings evaluate to zero, so 0 == 'true' is TRUE, but 0 === 'true' is FALSE. The string true has not been cast to a boolean value, but is being compared as a string to the zero. The zero is left as an int value, rather than cast as a boolean. So ultimately you get:

// string 'true' casts to int 0
0 == 0 // true

试试这个:

echo intval('true');
// 0
echo intval('some arbitrary non-numeric string');
// 0

查看PHP 类型比较表.一般来说,在 PHP 中进行布尔比较时,类型不一样(在这种情况下是 int 到 string),使用严格比较是有价值的.

Review the PHP type comparisons table. In general, when doing boolean comparisons in PHP and types are not the same (int to string in this case), it is valuable to use strict comparisons.

这篇关于PHP 类型转换混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆