Re: [RFC] Nullable Casting
| From: | Stephen Reay | Date: | Mon, 08 Apr 2019 10:24:47 +0000 |
| Subject: | Re: [RFC] Nullable Casting | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-105143@lists.php.net to get a copy of this message | ||
> On 8 Apr 2019, at 16:35, Benjamin Morel <benjamin.morel@gmail.com> wrote:
>
>> register_cast_function('?int', 'castToIntOrNull');
>
> I would quite oppose such a generic implementation, as it might have
> unexpected consequences in other parts of the codebase : it's a global
> configuration set at runtime.
>
> I quite like the idea of nullable casting though, as I've come across a few
> cases myself where this would have been useful and would have made the code
> more concise/readable.
>
> Ben
>
> On Mon, 8 Apr 2019 at 04:55, Dan Ackroyd <Danack@basereality.com> wrote:
>
>> On Sat, 6 Apr 2019 at 08:53, Guilliam Xavier <guilliam.xavier@gmail.com>
>> wrote:
>>>
>>> Hello internals,
>>>
>>> David and I would like to open the discussion on our joint RFC:
>>>
>>> https://wiki.php.net/rfc/nullable-casting
>>>
>>> Mainly, it would enable to use e.g.
(?int)$x besides
>>> (int)$x.
>>>
>>
>> I'm guessing you don't actually have ths function getIntOrNull() in
>> your code-base? To help me understand where this would be useful,
>> could you provide some 'real-world' code where this would be useful?
>>
>> By the way, this RFC is a special case of something that could be far
>> more generic. If it was possible to register callbacks to be used when
>> casting, people could do something like this:
>>
>> function castToIntOrNull($value)
>> {
>> if ($value === null) {
>> return null;
>> }
>>
>> return (int)$int;
>> }
>>
>> register_cast_function('?int', 'castToIntOrNull');
>>
>> $x = (?int)getIntOrNull();
>>
>>
>>> Additionally, it was requested on the mailing list to consider adding
>>> support of nullable types to the settype() function,
>>> e.g. settype($variable, "?int")
>>
>> Someone probably needs to make an argument for it to be in core,
>> rather than just saying that it's something that could be done.
>>
>> cheers
>> Dan
>> Ack
>>
>> --
>> PHP Internals - PHP Runtime Development Mailing List
>> To unsubscribe, visit: http://www.php.net/unsub.php
>>
>>
I’ve come across this pattern (string variable contains a number or nothing) myself, but it also
then makes me think - if your target ’type’ is ?int and you pass an empty string,
wouldn’t you expect to get null rather than 0 ?