Re: switch with case 0 [message #182630 is a reply to message #182612] |
Mon, 19 August 2013 08:18 |
Thomas 'PointedEars'
Messages: 701 Registered: October 2010
Karma:
|
Senior Member |
|
|
Thomas Mlynarczyk wrote:
> Norman Peelman schrieb:
>> That's why it says "foo" = 0. Now is "foo" really 0, no - but it sure
>> isn't greater than 0.
>
> In order to compare "foo" and 0 one would need either to convert the
> number 0 to a string ("0" would be the most reasonable result) or
> convert "foo" to a number (not reasonably possible). PHP, unfortunately,
> chooses the unreasonable alternative.
When you consider the possibility that a request parameter may or may not be
present, and you wanted an easy way to check this, like
if ($param)
{
// …
}
it does not look that unreasonable anymore.
The argument can be made that "0" is something, while "" is nothing. I
cannot find it reasonable by any measure that "foo" should be equal to 0.
"foo" certainly is something, while at the same time the argument can be
made that 0 is a mathematical “nothing” (the neutral element towards
addition).
But PHP, after all, also allows for strict comparison to avoid this problem.
Why do you not use it, and then complain about the language (with dubious
assertions about it, BTW)?
if ($param && $param !== "0")
{
// …
}
>> PHP looks at the string in question one character
>> at a time and builds a number until a non-numeric character is reached
>
> I am aware of all that. It was decided to make PHP work that way. I was
> merely pointing out that I consider it a very unfortunate decision to
> cast strings to numbers instead of the other way round.
I think it is the natural result of PHP being the *P*HP *H*ypertext
*P*reprocessor.
BTW, because of discussions like this one, switch-case has been either
removed in an early version from or is never going to be introduced into
Python, another programming language that uses dynamic type-checking (we
should lose the term “loose typing”, it is too loose to be useful). You
have to write
if foo == 1:
pass
elif foo == 2:
pass
elif foo == 3:
pass
else:
pass
and that is precisely what you should do in PHP if the type matters:
if ($foo === 1)
{
// …
}
else if ($foo === 2)
{
// …
}
else if ($foo === 3)
{
// …
}
else
{
/* default */
}
PointedEars
--
var bugRiddenCrashPronePieceOfJunk = (
navigator.userAgent.indexOf('MSIE 5') != -1
&& navigator.userAgent.indexOf('Mac') != -1
) // Plone, register_function.js:16
|
|
|