Hi,
There are really two questions - at some point in programming PHP these past 2 years I started avoiding the null coalescing operator (??), but I don’t really know why since they all use 7.2 and the docs say the operator is available starting in 7.0.
Is the null coalescing operator safe in 7.2 and up?
Will it store null if there’s an exception generated, especially indexing a nested array and trying to Index on null or undefined?
Does isset() catch exceptions and return null as well? Or will it throw an exception?
Thanks!
php 7.4 - What is null coalescing assignment ??= operator in PHP 7.4 - Stack Overflow
Here's a quick tip: you can use the null coalescing assignment operator for easy memoisation in PHP 7.4
Null coalescing assignment operator ??= is now confirmed for PHP 7.4
Does PHP 7.2 and up support null coalescing operators that nullify exceptions?
What is the syntax of the null coalescing operator?
$variable = $value ?? $default;
Here, $value is checked first. If it is null, $default is used instead.When should I use the null coalescing operator?
Does the null coalescing operator work with functions?
$username = getUserName() ?? 'Guest';Videos
From the docs:
Coalesce equal or ??=operator is an assignment operator. If the left parameter is null, assigns the value of the right parameter to the left one. If the value is not null, nothing is done.
Example:
// The following lines are doing the same
$this->request->data['comments']['user_id'] = $this->request->data['comments']['user_id'] ?? 'value';
// Instead of repeating variables with long names, the equal coalesce operator is used
$this->request->data['comments']['user_id'] ??= 'value';
So it's basically just a shorthand to assign a value if it hasn't been assigned before.
Null coalescing assignment operator chaining:
$a = null;
$b = null;
a ??=
c;
print $b; // c
print $a; // c
Example at 3v4l.org