Re: [RFC] [DISCUSSION] Improve null-coalescing operator (??) adding empty check (??:)
| From: | Lito | Date: | Thu, 22 Mar 2018 13:45:31 +0000 |
| Subject: | Re: [RFC] [DISCUSSION] Improve null-coalescing operator (??) adding empty check (??:) | ||
| References: | 1 2 3 4 5 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-101997@lists.php.net to get a copy of this message | ||
This is a RFC karma request for my wiki account.
I want to create a RFC with my proposal: Improve null-coalescing operator (??) adding empty check (??:)
First list message is: http://news.php.net/php.internals/101606
The main idea is simplify "empty" check on non existing keys or object attributes. Same as "?:" but also checking undefined.
Current check:
$value = empty($user->thisOptionalAttributeCanBeEmptyOrNotExists) ? 'without value' : $user->thisOptionalAttributeCanBeEmptyOrNotExists;
New feature:
$value = $user->thisOptionalAttributeCanBeEmptyOrNotExists ??: 'without value';
I think that could be very usefull on inline "exists" + "not empty" checks with a more clear code.
It's possible?
Thanks,
Lito.
On 17/01/18 19:47, Lito wrote:
On 17/01/18 19:43, Andrey Andreev wrote:Hi, On Wed, Jan 17, 2018 at 8:28 PM, Lito <info@eordes.com> wrote:Yes, I think that: $foo = $foo ??: 'default'; Is more clear and with less code than: $foo = empty($foo) ? 'default' : $foo; As ?? does. Regards, Lito.No $foo ?: 'default' , it's only equivalent to (isset($foo) && $foo) ? $foo : 'default' if $foo exists. Also PHP has added ?? as null-coalescing operator that works with undefined variables/attributes/keys, my proposal is an improvement over this one. I don't want to endorse usage of undefined variables, can be used in a large set of situations, like object attributes, array keys, etc... Anyway thanks for your feedback. Lito.There is a shorter version:empty($foo) ? 'default' : $foo;And I think that's quite convenient for the few use cases it has (refer to Nikita's reply). Cheers, Andrey.