Re: [RFC] Safe Casting Functions
| From: | Andrea Faulds | Date: | Wed, 19 Nov 2014 14:49:39 +0000 |
| Subject: | Re: [RFC] Safe Casting Functions | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-78999@lists.php.net to get a copy of this message | ||
> On 19 Nov 2014, at 08:33, Anatol Belski <anatol.php@belski.net> wrote:
>
> while briefly looking through the conversion examples, i see some weird
> results
>
> string(5) “31e+7” - shouldn't this be valid for int?
The trend seems to be to consider things with exponents or decimal points as floats. Even though
there’s a case for supporting it for ints, (int) and intval() don’t work with exponents, so
to_int() shouldn’t either.
> string(4) “0x10” - hex, but that's int, no?
Supporting hex is a rather obscure use-case. Also, (int) and intval() don’t support it.
> string(3) “010” - octal, but that's int, no?
While allowing leading zeroes would be nice, octal causes problems. In particular, 0-prefixed
strings aren’t handled consistently. Some things deal with them as decimal, others deal with them
as octal. Because the user’s intent isn’t clear, we can’t support them, and I assume this is
why FILTER_VALIDATE_INT doesn’t support them.
> string(4) “10.0” - this would be casting to 10, so int valid
Allowing .0 for an int doesn’t feel right. What do we do for “10.01”? Reject it? That seems
rather arbitrary when we would be allowing “10.00”. So it’s not accepted.
> object(Stringable)#2 (0) {} - and similar actually, what if _toString()
> returns some int/float literal? that should pass as well, no?
__toString() always errors if it doesn’t return a string, I see no reason to change that.
> Generally I'd say no to this RFC. The current casting is not perfect, but
> as for me - the one suggested is highly questionable as well. IMO as long
> as there are no proper strict types in PHP, any other rule set for casting
> would be just another coordinate system for the same, which isn't worth
> while at least.
Something like this RFC is a necessary prerequisite for strict types. Without it, there’s not a
convenient way to do a safe conversion. If we just add strict types, people will blindly use (int)
or intval() and magically, garbage input will be transformed (through the magic of ignoring
everything in the string that doesn’t look like an int) into apparently sane input and apps will
do dangerous things when presented with bad user input.
--
Andrea Faulds
http://ajf.me/