Numeric Type
| From: | Deleu | Date: | Tue, 02 Jun 2020 15:09:41 +0000 |
| Subject: | Numeric Type | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-110334@lists.php.net to get a copy of this message | ||
Hello Internals,
I'd like to know what would be people's feelings towards having a
numeric
type. I remember reading the nullable casting RFC (
https://wiki.php.net/rfc/nullable-casting)
and it's discussion (
https://externals.io/message/105122). Although I
would very much prefer to
have nullable casting, it seems to be a bit controversial and perhaps
Numeric Type could be a middle ground solution.
The primary intent would be to safely pass around input that usually comes
from HTTP, CI or Database. Whenever interacting with these data providers,
string is a common format. is_int will not return true for integer values
that are string, instead we need to rely on is_numeric. Similarly, I
think we could benefit from having foo(?numeric $value) as a type-safe
mechanism to transfer data around without having to forcefully check for
numeric value before casting. If we simply (int) $value, we may end up
casting null to 0. Type-hitting ?numeric could be a
compromise.
```
foo(?int $number);
foo($_GET['param']); // TypeError: foo() expects int or null, string given
foo((int) $_GET['param']); // null becomes 0
foo($_GET['param'] ? (int) $_GET['param'] : null); // expected behavior
bar(?numeric $number);
bar($_GET['param']); // would work with any value that passes is_numeric()
```
I also think this approach have a benefit over PHP 8 Union Type
(int|string) because is_numeric() does not return true for string values
and for consistency the numeric type-hint would behave similarly.
Thoughts?
--
Marco Aurélio Deleu