php 类型转换为布尔值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8380452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 04:34:43  来源:igfitidea点击:

Type-casting to boolean

phpcastingboolean

提问by Paris Liakos

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?

当然第二次返回是正确的,但为什么在第一次 php 返回一个意外的值?

回答by ruakh

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

实际上并没有看起来那么奇怪。(bool)具有比 更高的优先级==,因此:

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 2also essentially gets cast to bool(since this is a "loose comparison"), so it's equivalent to this:

由于type juggling, the2也基本上被强制转换为bool(因为这是一个“松散比较”),所以它相当于:

var_dump(true == true);

or this:

或这个:

var_dump(true);

回答by Jon

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 2to trueand comparing, ultimately producing true.

通过转换2true和比较来评估,最终产生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.

看到它在行动

回答by Jon

I use this way:

我用这种方式:

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

回答by Ankur Kumar Singh

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

您编写语句 ((bool) 1==2) 的方式将始终返回 true,因为它将始终执行如下流程的代码:

First, it will execute

首先,它会执行

(bool)1

and (bool) 1 will return true.

并且 (bool) 1 将返回 true。

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

现在,由于 (bool)1 在第二步为真,您的陈述将类似于

true ==2

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

由于如果我们将 2 类型转换为布尔值,它将返回 true,因此在最终状态下,您的语句将类似于

true == true

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

这显然会返回true。同样的事情我在我的帖子PHP 类型转换中也解释过。