Newsgroups: php.internals Path: news.php.net Xref: news.php.net php.internals:105207 Return-Path: Delivered-To: mailing list internals@lists.php.net Received: (qmail 694 invoked from network); 10 Apr 2019 17:36:47 -0000 Received: from unknown (HELO localhost.localdomain) (76.75.200.58) by pb1.pair.com with SMTP; 10 Apr 2019 17:36:47 -0000 To: internals@lists.php.net References: Date: Wed, 10 Apr 2019 15:33:58 +0100 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:60.0) Gecko/20100101 Thunderbird/60.6.1 MIME-Version: 1.0 In-Reply-To: Content-Type: text/plain; charset=utf-8; format=flowed Content-Language: en-GB Content-Transfer-Encoding: 7bit X-Posted-By: 94.0.205.114 Subject: Re: [PHP-DEV] [RFC] Nullable Casting From: markyr@gmail.com (Mark Randall) Message-ID: On 10/04/2019 13:03, Benjamin Morel wrote: > There is only one, if we align the semantics of explicit and implicit > casting: you wouldn't expect this: > > function test(?int $bar) { var_export($bar); } > test("abc"); > > ...to output 'null'? (Continuing from my previous post in a different thread...) IMHO a cast such as ([?]type) would be better described as passing a mixed value through a function which has a return type of whatever is in the cast... the mechanics of that function determine what is returned, so long as it conforms to the cast type. A cast should always either return a value that would be accepted by a function argument of an identical type to the cast, or it should throw an exception. function x(T $value) { ... } x(T) - Always OK x((T)$var) - Always OK x($var) - Function may throw a TypeError if it cannot be converted in a very strict manner. To my mind, (?int) is quite explicit, in that it returns an integer or null, and it is quite logical to expect it to return null in lieu of throwing a TypeError if a conversion is not possible. Naturally, (?int)null would return null. I see a lot of potential use in (?int)$value ?? $default. Equally I see a lot of use in the following to nullify unexpected inputs such as if $_GET['something'] was an array: $input = (?string)$_GET['input'] ?? ''; -- Mark Randall