了解PHP类型强制 [英] Understanding PHP Type Coercion

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

问题描述

我看到这小段代码正在逃避我的理解:

<?php

$a = '0e462097431906509019562988736854';
$b = '0e830400451993494058024219903391';

var_dump($a == $b);

哪个会输出:

bool(true)

我了解到,使用==时,PHP将尝试进行模糊比较,并在类型之间进行无提示转换以执行比较.我理解的是为什么PHP似乎认为这两个字符串相同.我会想到,因为$a$b是字符串,所以不需要进行类型转换.

我不明白什么?

解决方案

我认为本文对此进行了很好的解释:

类型强制比较运算符会将数字字符串转换为数字

在这里引用主要问题:

根据 php language.operators.comparison ,类型强制比较运算符将强制两个即使它们都已经是字符串,即使它们都看起来像数字,操作数也要浮点数:

其中两个strings都使用指数表示法,因此被视为数字字符串,进行松散比较(==),在实际上松散"比较它们之前将这些strings强制为floats.

作为最佳实践并防止意外行为,请始终尝试使用身份平等(===),尤其是

I saw this small piece of code that is evading my understanding:

<?php

$a = '0e462097431906509019562988736854';
$b = '0e830400451993494058024219903391';

var_dump($a == $b);

Which will output:

bool(true)

I understand that when using == PHP will attempt fuzzy comparison, silently converting between types in order to perform the comparison. What I'm not understanding is why PHP seems to think these two strings are the same. I would have thought since $a and $b are strings, that no type conversion would need to take place.

What am I not understanding?

解决方案

I think this article explains it pretty well:

Type-coercing comparison operators will convert numeric strings to numbers

Just to quote the main issue here :

According to php language.operators.comparison, the type-coercing comparison operators will coerce both operands to floats if they both look like numbers, even if they are both already strings:

where both strings are using exponential notation, hence are treated as numeric strings, making loose comparison (==), coerce these strings to floats before actually "loosely" comparing them.

As a best practice and to prevent unexpected behaviour, always try to use identity equality (===), especially when dealing with strings

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

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