PHP:了解字符串类型的杂耍 [英] PHP: Understanding string type juggling

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

问题描述

如果我在PHP中将 $ var 设置为 string ,则该变量在任何情况下的计算结果均为 true :

If I set $var to a string in PHP, that variable will evaluate to true in any conditions:

$var = "foo";
if ( $var ) {
    echo 'I will be printed';
} else {
    echo 'I will not be printed';
}

我了解我的上述条件会自动键入杂耍,以便将 $ var 转换为 bool .

I understand that my condition above automatically does type juggling so that $var is converted in a bool.

现在,如果将 $ var 强制转换为 integer ,则得到 0 :

Now, if I cast $var to an integer, I get 0:

var_dump( (int)$var ); // int(0)

0 是一个 fassy 值,当转换为 bool 时,该值将变为 false :

0 is a falsy value which becomes false when converted to a bool:

$zero = 0;
var_dump( (bool)$zero ); // bool(false)

考虑到上述情况,为什么我的条件不打印我不会被打印"?

Considering the above, why doesn't my condition print "I will not be printed"?

推荐答案

类型变戏法不是无损的.它会带来潜在的数据丢失.

Type juggling isn't lossless. It comes with potential loss of data.

例如...

var_dump( strval(intval("foo"))); // string(1) "0"

但是如果你要写...

But if you were to write...

if( "foo" == "0") // non-strict comparison intended

您肯定不会期望它运行!确实不是.

You would surely not expect it to run! And indeed it doesn't.

因此,由于类型更改会带来数据丢失,因此您不能指望转换是等效的.换句话说, boolval(intval($ var)) boolval($ var)不必相同.

So because type changes come with data loss, you can't expect conversions to be equivalent. In other words, boolval(intval($var)) and boolval($var) need not be the same.

如果您想严格比较,请使用以下内容:

If you want to be strict in your comparisons, use something like this:

if( is_string($var) && $var !== "") // is not the empty string

(可以说!== 是多余的,而!= 可以很好地工作,但可以说整个条件都是过大的)

(Arguably !== is redundant and != works fine, but arguably this whole condition is overkill)

这篇关于PHP:了解字符串类型的杂耍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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