Re: make casts more strict in PHP 7
| From: | Andrea Faulds | Date: | Thu, 11 Sep 2014 02:03:34 +0000 |
| Subject: | Re: make casts more strict in PHP 7 | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-77145@lists.php.net to get a copy of this message | ||
On 10 Sep 2014, at 18:41, Rowan Collins <rowan.collins@gmail.com> 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/