Re: [RFC] Scalar Type Hinting With Casts (re-opening)
| From: | Arvids Godjuks | Date: | Mon, 14 Jul 2014 13:40:38 +0000 |
| Subject: | Re: [RFC] Scalar Type Hinting With Casts (re-opening) | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-75459@lists.php.net to get a copy of this message | ||
2014-07-14 15:41 GMT+03:00 Rowan Collins <rowan.collins@gmail.com>:
> Arvids Godjuks wrote (on 14/07/2014):
>
> We already have quite good implementation for the array and object hints,
>> they do their job and do it good. No need to change those at all - leave
>> them as is - no need to add magic with casts and all that. Function/method
>> requires an array? Make casts explicitly and pass it an array and not an
>> integer.
>>
>
> Yes, I totally agree. What I don't think makes sense is for the keyword
> "array" in a function signature to mean "error if a string is passed", but
> the keyword "int" in exactly the same place to mean "happily accept any
> string (or even an array) and cast it to int, even if it's a lossy
> conversion".
>
> If there is to be a short-hand for casts in function signatures, it should
> not reuse the current syntax for type assertions, as they are not
> equivalent facilities.
>
>
> But this automatic
>> casting should work only between string, integer, float, bool and null
>> types and only between these. No automatic casting of these 5 to arrays or
>> objects.
>>
>
> Rather than special-casing this for "static types" (despite the fact that
> arrays *can* be cast from other types) I would prefer to see it only happen
> where it can be *lossless* (which is never the case for arrays, thus making
> the current logic consistent with the new rule). This is essentially what
> the current RFC proposes.
>
> I don't think that's actually overthinking it any more than the scalar vs
> non-scalar version would, as it's a pretty easy rule to express. Broadly,
> if (source_type)(target_type)$var == $var, that's a lossless cast. (There
> are a couple of odd exceptions with very specific values, such as
> (int)(array)1 == 1, but it's not too much of a stretch to say "all array
> casts are considered lossy".)
There is no special casing, Array and Object type hints are already
implemented and are in the language for quite a long time. Just don't touch
them, that's all I ask. Implement scalar hints and because of the nature of
PHP - they need to have type casting built in. Otherwise you are forced to
typecast on your own everything that comes from the outside sources:
GET/POST/Databases/API's/REST/the whole lot. If it was a correct string
that was converted to an int/float without any data loss - keep calm and
carry on.