问题
$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