22

Once I stumbled with php7 code with operator ??=. I tried to search, what it clearly does, but could not find easily. I tried to read out the php operators and even most official resources have all operators description and even compound operators like .=, +=, but there are no description for ??=

For example, PHP Operators keeps descriptions of all operators, as straight form (., +), as compound (.=, +=), but there is no ??=, and because of that I firstly was confused and thought it's something totally another. The issue is simple and obvious, but the whole case is a bit confusing, that's why I try to help other php-beginners like me

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Green Joffer
  • 580
  • 1
  • 4
  • 16
  • thanks, you are right, but, you see, you just can't search it in casual way, 'cause, for example, google for your request '??=' returns nothing usefull - as for "double qestion mark equal sign" too, so you just can't find out, where information is – Green Joffer Oct 20 '20 at 12:14
  • 1
    Check out https://wiki.php.net/rfc/null_coalesce_equal_operator – Siva Apr 26 '21 at 15:28

1 Answers1

23

So eventually I decided to write code and watch by myself - how it works and what it does.

In PHP7.0 was added the Null Coalescing operator:

$username = $_GET['username'] ?? 'not passed'; 

Our $username will have $_GET['username'] value - if it exists and not null, otherwise $username will get 'not passed' string. But sometimes you can have a situation, when you need to check for existence and not-nullability the variable itself:

$first_test = $first_test ?? 'not started';

And in this situation you can use a compound version of null coalescing operator - '??=':

$first_test ??= 'not started';

That's it, just compound version of '??' for the cases, where you check the itself variable.

Green Joffer
  • 580
  • 1
  • 4
  • 16
  • 5
    `??=` was only added in php 7.4 and up - [demo](https://3v4l.org/GTN0r) - [documentation](https://www.php.net/manual/en/migration74.new-features.php#migration74.new-features.core.null-coalescing-assignment-operator) – DarkBee Oct 20 '20 at 08:50
  • thanks, did not know, that operator and its shorthand were released in different versions – Green Joffer Oct 20 '20 at 12:11