Re:PHP cheat: ==, ===, empty(),is_null(),isSet()
by apexauk on Monday August 25, 2008 @09:18PM
(#286645)
in PHP "foo" == 0 due to how php handles type juggling - the string is converted to an integer before the comparison, with strings that don't contain numbers converted to 0. so "foo" == 0 and "0" == 0 but "1" != 0.
[ Parent
| on HN ]
Re:PHP cheat: ==, ===, empty(),is_null(),isSet()
by time_management on Monday August 25, 2008 @09:24PM
(#286647)
This makes more sense, but I still find it odd and disagreeable. I tend to prefer that my programs fail loudly, so I'd write string -> int conversion to raise an exception on seemingly non-numerical input like "foo", "ba6r.5", "pwn3d", etc. Then again, admittedly I know very little about web development. Is it not practical to do this?
Re:PHP cheat: ==, ===, empty(),is_null(),isSet()
by Zak on Monday August 25, 2008 @10:41PM
(#286699)
There is nothing special about web development that makes implicit typecasting or returning an arbitrary value when a cast fails instead of raising an exception a good idea. Another reasonable option is to return NaN (Javascript does this) or null.
Re:PHP cheat: ==, ===, empty(),is_null(),isSet()
by apexauk on Tuesday August 26, 2008 @06:38AM
(#286944)
agree about failing loudly when bad stuff happens - but exceptions are best reserved for truly exceptional circumstances. in webdev everything arrives from the browser as a string so implicit casting is more of the norm. if your user enters something dumb into the quantity field of your shopping cart it doesn't really warrant abandoning the rest of their input and leaping back up the call stack to a "misson failed"-level error handler.
functions like is_numeric('string') exist for the rarer situations where things like this actually matter, but php's default way is simply reflective of it's nature as a loosely-typed language.