Re: Numeric Type

From: Date: Tue, 09 Jun 2020 09:37:29 +0000
Subject: Re: Numeric Type
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-110444@lists.php.net to get a copy of this message
Hi all, One thought is that is_numeric(true) will return false, but the int type-hint will accept it as a 1. The other thought I had was no one mentioned floats, so maybe a number type could be argued for but with mixed types that can be solved by int|float now. Thanks, Peter On Tue., Jun. 2, 2020, 08:10 Deleu, <deleugyn@gmail.com> wrote: > 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 >

« previous php.internals (#110444) next »