Re: [PHP-DEV] make casts more strict in PHP 7
[email protected] (Andrea Faulds)
| Newsgroups | php.internals |
|---|---|
| Message-ID | <[email protected]> |
On 10 Sep 2014, at 18:41, Rowan Collins <[email protected]> wrote: > I think this came up during the previous discussion, and I actually think it would be quite nice to have some functions both to perform a "strict"/"safe" cast (and raise E_CATCHABLE_ERROR or perhaps throw TypeCastException), and to check if a variable *can* be thus cast (validating integers is unnecessarily complicated at the moment). > > Either: > mixed safe_cast(mixed $var, string $type) > boolean can_safe_cast(mixed $var, string $type) > e.g. > if ( can_safe_cast($_GET['i'], 'int') ) > $i = safe_cast($_GET['i'], 'int'); > > Or, to avoid representing the type with a string arg, a whole set of functions: > int safe_cast_int(mixed $var) > boolean can_safe_cast_int(mixed $var) > float safe_cast_float(mixed $var) > boolean can_safe_cast_float(mixed $var) > etc > > The first avoids creating so many new functions, but perhaps some constants should be defined for the argument, based on the values returned by gettype(): > > PHP_TYPE_INT = "integer" > PHP_TYPE_FLOAT = "double" > PHP_TYPE_STRING = "string" > PHP_TYPE_ARRAY = "array" > PHP_TYPE_OBJECT = "object" > PHP_TYPE_RESOURCE = "resource" > PHP_TYPE_NULL = "NULL" > > > Of course, we'd then need to agree exactly which casts are considered "safe"… You know, “int”, “float”, “string” etc. aren’t currently reserved words. We could add functions, or even make them reserved words and add internal functions (à la isset), so int(‘2’), float(‘2.0’), string(‘test’) etc. Or perhaps class-like constructors? $a = new int('2'); ? Would kinda make sense given some people want to add methods to primitive types. -- Andrea Faulds http://ajf.me/