By larowlan on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
9.3.x
Introduced in version:
9.3.0
Issue links:
Description:
All usages of isset in ternary operations have been replaced with null coalesce
Before
isset($composerJsonData['require-dev']) ? $composerJsonData['require-dev'] : [];
After
$composerJsonData['require-dev'] ?? [];
Impacts:
Module developers
Comments
Warning question
Is this a new PHP thing? As of what version?
One of the things that bit me when doing PHP work is that if would sometimes do something like (following your example):
if ($composerJsonData['require-dev']) { ... }But then PHP would issue a warning sometimes if require-dev wasn't a key in the array already, so I would have to "bulletproof" my PHP code to check for that, too, to eliminate the warning:
if (isset($composerJsonData['require-dev']) && $composerJsonData['require-dev']) { ... }D9 requires PHP 7.3, so I guess my question for my own understanding is that if you do this, will it generate warnings?
One other concern I have is code readability. Will this increase the reading-level, so to speak, of the underlying code?
Tested this out
I wrote a simple test w/ PHP 7.4 to answer my own question and didn't see any warnings:
Ran this on an older server with PHP 5.6 and that failed, but that's to be expected since it's a new language construction and acceptable since D9 requires PHP 7.3+.
I also ran this on PHP 7.3 and got the same result as 7.4 without any warnings.
I then updated the script to work with 5.6, just to see the warnings:
Output:
Anyway, excuse my curious ramblings as I am learning something new (and maybe this may be helpful to others).
Resource link
Another similar construct is called the "elvis operator" (not sure if that's the official name). I get this operator and null coalescing confused often, but this page has helped me understand them: https://stackoverflow.com/questions/34571330/php-ternary-operator-vs-nul...
Null coalescing operator is part of PHP 7
Null coalescing operator is part of PHP 7.0. See php.net documentation under "Migrating from PHP 5.6.x to PHP 7.0.x" > Null coalescing operator. This should answer your questions.