Videos
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!
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;
$c = 'c';
$a ??= $b ??= $c;
print $b; // c
print $a; // c
Example at 3v4l.org