[nycphp-talk] Re: Weird Switch Behavior
Michael B Allen
ioplex at gmail.com
Tue Sep 9 23:45:39 EDT 2008
On Tue, Sep 9, 2008 at 10:56 PM, Hans Zaunere <lists at zaunere.com> wrote:
>> Nevermind - $key is an int so 'foo' is being cast to an int which
>> evaluates to 0.
>>
>> I think I would prefer that switch be a little more explicit.
>>
>> > switch ($key) {
>> > case 'foo':
>> > case 'bar':
>> > echo "[$key][$val]\n";
>> > break;
>> > }
>> > }
>> >
>> > $ php -f switch.php
>> > [foo][1]
>> > [bar][2]
>> > [0][zap]
>
> Should switch be more explicit, or should the programmer? :) Don't depend
> on auto type casting...
That's what I'm saying.
In this case PHP looks at $key and sees (int)0. So now it auto type
casts 'foo' to an int which for any string yields (int)0 and thus the
case matches the 0 => 'zap' element unexpectedly. If switch used a
typed comparison it would not auto type cast and it would compare
(int)0 to (string)'foo' and because the types do not match I would get
the expected results.
But of course if switch used a typed comparison you would have to code
something like:
$str = '5';
switch ($str) {
case 5:
// no match ?!
break;
case 'foo':
...
as:
$str = '5';
switch ($str) {
case 5:
case '5':
// ahhh, now it matches
break;
case 'foo':
...
with double cases which people would no doubt be hee'n and haw'n over to no end.
M
--
Michael B Allen
PHP Active Directory SPNEGO SSO
http://www.ioplex.com/
More information about the talk
mailing list