Re: [RFC] Safe Casting Functions
| From: | Bob Weinand | Date: | Wed, 22 Oct 2014 08:37:11 +0000 |
| Subject: | Re: [RFC] Safe Casting Functions | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-78223@lists.php.net to get a copy of this message | ||
I know we have that already discussed a lot now, but I’d like to expose my points on the return
value here:
I imagine code like (supposing that we ever will have scalar typehints):
function acceptsInt (int $i = null) {
if ($i === null) {
$i = 2 /* default value */;
}
/* do something with $i */
}
When we return false:
acceptInt(($tmp = to_int($_GET["userinput"])) === false ? null : $tmp);
When we throw an exception:
try {
acceptInt(to_int($_GET["userinput"]));
} catch (CastingException $e) {
acceptInt(null);
}
When we just return null:
acceptInt(to_int($_GET["userinput"]));
Also, when we want to pass a default value defined outside of the function, it’s a lot easier now
with the coalesce operator:
acceptInt(to_int($_GET["userinput“]) ?? 2 /* default value */);
Also, independently of possible scalar typehints:
Generally exceptions are also a bad idea as the casts probably will be used on external input and
exceptions are **not** a way to handle malformed user input. Really not.
Furthermore, false is a bad idea in the same sense (if we get scalar type hints once), because
people then might just catch the EngineException…
Also, null means "no value"; that’s exactly what we need. If the to_{type}() functions
cannot return a meaningful value, just return "no value", that means null. And not false,
which is a real value.
That’s why I strongly feel that null is the only true thing to return here.
Thanks,
Bob
> Am 21.10.2014 um 00:57 schrieb Andrea Faulds <ajf@ajf.me>:
>
> Good evening,
>
> I am presenting a new RFC to add a set of three functions to do validated casts for scalar
> types:
>
> https://wiki.php.net/rfc/safe_cast
>
> Please read it.
>
> Thanks!
> --
> Andrea Faulds
> http://ajf.me/