Why does this code output 1?

妖精的绣舞 提交于 2019-12-23 01:52:28

问题


$t = true;
switch($t)
{
    case 1*2:
        echo 1;
}

回答1:


The manual for switch/case says:

Note that switch/case does loose comparison.

And true == 2 is true.




回答2:


A switch statement does loose comparison between the tested expression and the expressions in the case labels to the type.

In this case, this means that it the compiler determines if true == 2. Since any nonzero integer compares equal to true, the branch is taken and echo 1; is executed.

Here's a less intuitive example where the exact same mechanism is in effect. You can explain it with the same logic:

$foo = 'hello';
switch($foo) {
    case 'A' || 'B':
        echo "Test succeeded";
}

I 've used this example in the past when teaching PHP to newbies, to get them to understand how a loosely typed language works.




回答3:


In PHP (and in the most of programming languages) a non-zero value means true when is treated in a conditional statement. In this case $t (true) is equal to any number different than zero, so it matches the case condition. The output will be 1.



来源:https://stackoverflow.com/questions/5327335/why-does-this-code-output-1

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