Re: [RFC] Nullable and non-nullable cast operators
| From: | Rowan Tommins [IMSoP] | Date: | Fri, 31 Oct 2025 13:38:44 +0000 |
| Subject: | Re: [RFC] Nullable and non-nullable cast operators | ||
| References: | 1 2 3 4 5 6 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-129029@lists.php.net to get a copy of this message | ||
On 31 October 2025 09:05:35 GMT, Alexandre Daubois <alex.daubois+php@gmail.com> wrote:
>We did some research with Nicolas about deprecating casting null
>instead of proposing a new
(!type) operator. The idea did not
>make
>it, and we explained why in this new section:
>https://wiki.php.net/rfc/nullable-not-nullable-cast-operator#alternative_considereddeprecating_null_casting
This highlights something that's been bugging me about this RFC: you've called the
"(!type)" syntax a "non-nullable cast", but that's actually the *least
significant difference* from existing casts. The *most significant difference* is that it can throw
a TypeError for an invalid value.
In fact I would argue that existing casts don't "accept null" at all - the behaviour
of (int)$foo can be adequately described something like this:
1. if $foo is already an int, return that
2. if $foo is a float, truncate it to an integer
3. if $foo is a numeric string, return the integer equivalent
4. if $foo begins with a numeric string, return the integer equivalent of that part
5. else, return integer zero
I may have missed some other cases, but there's no explicit rule for null, it's just
falling into the "else" clause at the end.
You would get the same answer from a hypothetical "cast($foo as int default 0)", except
that maybe we'd like to remove rule #4.
What you are proposing is a new syntax that changes step 5 to "else, throw a TypeError".
That might be a useful feature in some cases, but it's nothing to do with the title of the RFC.
Rowan Tommins
[IMSoP]