php类型比较的基础哲学 [英] Underlying philosophy behind php type comparisons
问题描述
因此,在php网站上有这个网页,显示比较不同值的结果:
http://php.net/manual/en/types.comparisons.php
这是一个有用的参考,但我宁愿不必访问此页面每次我想确保我做类型比较正确。所以我的问题是
在PHP上的类型比较逻辑背后有一些基本的哲学/推理吗?
$ b
例如,我可以看到,对于松散的比较:
- 1,-1,和-1可以被视为TRUE和0,并且0可以被视为FALSE;
- 使用yield TRUE比较数字的字符串值与数字本身; li>
但是在尝试建立模式时会变得有点毛。
直接转换为布尔值,这是它的工作原理。
- 所有非空数组都为真
- 所有对象都为true
然后,这些规则用于比较同一类型的变量:
对于不同类型的变量,上面列表中较高的类型被强制转换为低于比较的类型。
===
和!==
在比较之前,你应该注意对象只有 ===
如果他们是同一个实例。
真奇怪的是数组,如果它们有相同的键和值定义,它们是 ===
$ a = array(a=> 1,b=> 2);
$ b = array(b=> 2,a=> 1);
$ a == $ b; // true
$ a === $ b; // false
和 empty()
相当于!(bool)$ var
EXCEPTIONS
$ b
- 将数组转换为字符串将触发通知并无效地转换为
Array
- 将没有
__ toString
方法的对象转换为字符串会得到致命错误。 - 对象不会隐式转换为数组,因此任何时候将某个对象与数组进行比较都会产生假( UPDATE ),如果对象实现
ArrayAccess
接口)
So there's this page on the php site which shows the result of comparing different values:
http://php.net/manual/en/types.comparisons.php
This is a helpful reference, but I would rather not have to visit this page every time I want to make sure that I'm doing type comparison right. So my question is
Is there some kind of underlying philosophy/reasoning behind the logic of type comparisons on PHP?
For example, I can see that for loose comparisons:
- 1, -1, "1" and "-1" can be treated as TRUE and 0 and "0" can be treated as FALSE;
- Comparing the string value of a number against the number itself with yield TRUE;
but it becomes a bit hairy from then on trying to establish a pattern.
For casting directly to a boolean this is how it works.
- All string with a length > 0 are true
- All non 0 numbers are true
- All non-empty arrays are true
- All objects are true
Then these rules for comparing variables of the same type:
- Objects are equivalent if their properties are equal
- Arrays are equivalent if their keys and elements are equal
- Strings are equivalent if they would produce the same output
- Numbers are equivalent if they are mathematically equivalent
- Booleans are equivalent if they have the same value.
For variable of different types the type that is higher on the above list is cast to the one that is lower then the comparison is made.
===
and !==
operators don't cast prior to comparing but you should note objects are only ===
if they are the same instance.
The really odd one is arrays, they are ===
if they have the same keys and values defined in the same order.
$a = array("a"=>1, "b"=>2);
$b = array("b"=>2, "a"=>1);
$a == $b; // true
$a === $b; // false
and empty()
is equivalent to !(bool)$var
EXCEPTIONS
- Casting an array to a string will trigger a notice and unhelpfully cast as the text
Array
- Casting an object without a
__toString
method to a string will get you a fatal error. - Objects will not implicitly cast to an array, so any time you compare an object to an array it will yield a false (UPDATE confirmed that this is true even if object implemtents the
ArrayAccess
interface)
这篇关于php类型比较的基础哲学的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!