Req #66361 [Opn->Dup]: Risky behavior of switch statement
| From: | rasmus@php.net | Date: | Fri, 27 Dec 2013 20:39:30 +0000 |
| Subject: | Req #66361 [Opn->Dup]: Risky behavior of switch statement | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-183474@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=66361&edit=1
ID: 66361
Updated by: rasmus@php.net
Reported by: mmshfe at gmail dot com
Summary: Risky behavior of switch statement
-Status: Open
+Status: Duplicate
Type: Feature/Change Request
Package: SPL related
Operating System: Any OS
PHP Version: Irrelevant
Block user comment: N
Private report: N
Previous Comments:
------------------------------------------------------------------------
[2013-12-27 20:37:55] mmshfe at gmail dot com
Description:
------------
As mentioned in docs, switch statement is a loose type comparison tool. But this may be lead to a
serious bug in user products. It would be really better to force it to use strong type comparison
(or have an option such as an optional 2nd argument let the users to do so). In the real world, we
have no other loose type languages that behaves like this. For example, in JavaScript, the result is
fine. I mean, although being a loose type language is a good feature for PHP in overall; It should
not be led to unexpected results those not shown in any other language (even the other loose type
ones).
I really now the process flow. It uses if, elseif, else statements like this:
if($v == 'hello') {
echo 'Hello';
}
elseif($v == 'goodbye') {
echo 'Goodbye';
}
else {
echo 'Error';
}
And 'hello' is converted to integer (with intval('hello') or anything similar)
and because it does not contain an integer value at the beginning, it uses the default integer value
(zero) and so, the first case becomes true. All I want to say is that this behavior is incorrect
because approximately always it's not the behavior that the developer expected.
Test script:
---------------
$v = 0;
switch($v) {
case 'hello':
echo 'Hello';
break;
case 'goodbye':
echo 'Goodbye';
break;
default:
echo 'Error';
break;
}
Expected result:
----------------
Error
Actual result:
--------------
Hello
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=66361&edit=1