Type-casting to boolean

*爱你&永不变心* 提交于 2019-12-22 01:55:11

问题


Can someone explain me why this:

var_dump((bool) 1==2);

returns

bool(true)

but

var_dump(1==2);

returns

bool(false)

Of course the second return is correct, but why in the first occasion php returns an unexpected value?


回答1:


It's actually not as strange it seems. (bool) has higher precedence than ==, so this:

var_dump((bool) 1==2);

is equivalent to this:

var_dump(  ((bool) 1)   == 2);

or this:

var_dump(true == 2);

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);

or this:

var_dump(true);



回答2:


Because in the first example, the cast takes place before the comparison. So it's as if you wrote

((bool) 1)==2

which is equivalent to

true == 2

which is evaluated by converting 2 to true and comparing, ultimately producing true.

To see the expected result you need to add parens to make the order explicit:

var_dump((bool)(1==2));

See it in action.




回答3:


I use this way:

!!0 (false)
!!1 (true)



回答4:


The way you have written the statement ((bool) 1==2) will always return true because it will always execute the code like below flow:

First, it will execute

(bool)1

and (bool) 1 will return true.

Now since (bool)1 is true at second step your statement will be like

true ==2

Since if we will typecast 2 into boolean it will return true, at final state your statement will be like

true == true

Which will obviously return true. The same thing I have explained year back in my post PHP Type casting as well.



来源:https://stackoverflow.com/questions/8380452/type-casting-to-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!