类型转换为布尔 [英] Type-casting to boolean
本文介绍了类型转换为布尔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以向我解释为什么:
Can someone explain me why this:
var_dump((bool) 1==2);
返回
bool(true)
但是
var_dump(1==2);
返回
bool(false)
当然第二次返回是正确的,但是为什么在第一次php中返回一个意外值?
Of course the second return is correct, but why in the first occasion php returns an unexpected value?
推荐答案
实际上看起来并不奇怪. (bool)
的优先级高于==
,因此,此:
It's actually not as strange it seems. (bool)
has higher precedence than ==
, so this:
var_dump((bool) 1==2);
等效于此:
var_dump( ((bool) 1) == 2);
或者这个:
var_dump(true == 2);
由于类型变戏法, 2
本质上也强制转换为bool
(因为这是松散比较"),因此等效于此:
Due to type juggling, the 2
also essentially gets cast to bool
(since this is a "loose comparison"), so it's equivalent to this:
var_dump(true == true);
或者这个:
var_dump(true);
这篇关于类型转换为布尔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文