The null coalescing operator ?? available since PHP 7.0 “returns its first operand if it exists and is not null; otherwise it returns its second operand”. This works more or less everywhere you can think of to use it:
echo $nonexistent ?? 'a'; // outputs 'a'
echo $nonexistent[5] ?? 'b' // outputs 'b'
echo $nonexistent['hello'] ?? 'c' // outputs 'c'
echo $nonexistent->evenMoreNonexistent ?? 'd' // outputs 'd'
The only place it doesn’t work is if you try to use it with a nonexistent function/method, or a method on a variable that either doesn’t exist or is not an object:
$int = 5;
echo $int->stillNotHere() ?? 'e'; // throws exception
echo $nonexistent->allInYourMind() ?? 'f'; // throws exception
Unfortunately, due to all the fancy magic method stuff that happens in Laravel collections (or at least I’m assuming that’s why), attempting to access a nonexistent property on a collection object behaves sort of like a method call, in that it will throw an exception instead of returning NULL, which means the null coalescing operator won’t work:
$users = User::all();
echo $users->nonexistent ?? 'g'; // throws exception
Is there a (reasonably simple) way to get around this and make collection properties behave more like regular object properties?
(I know there are plenty ways to work around it using empty() and similar strategies, but I’m specifically looking for a way to transparently make collections work with the null coalescing operator.)