Reputation: 732
I am trying to understand how the null coalescing operator
does really work. So, I tested many examples after reading the documentation in php.net and some posts on stackoverflow.
However, I can't understand this code:
<?php
$x = false ?? 'stackoverflow';
var_dump($x); // bool(false)
since it's equivalent to (from php.net#null-coalescing)
isset(false) ? false : 'stackoverflow';
and since isset(false)
generates a fatal error
.
Could, please, someone explain to me?
Upvotes: 1
Views: 2175
Reputation: 357
Null coalescing operator returns its first operand if it exists and is not NULL;
Otherwise it returns its second operand.
In your case first operand is false so it is assigned to the variable. For e.g; if you initialize null to first operand then it will assign second operands value as shown.
$a = null;
$x = $a ?? 'abc';
var_dump($x);
Result :
string(3) "abc"
Upvotes: 2