I would like to omit checks for null in chained statements like
if($a && $a->$b && $a->$b->$c){
$d = $a->$b->$c;
}
and use optional chaining instead.
Is this possible or implemented in PHP?
According to this article "The null coalescing operator ( introduced in PHP 7) is represented like this ?? used to check if the value is set or null, or in other words, if the value exists and not null, then it returns the first operand, otherwise, it returns the second operand."
So you can easily do
$d = $a->$b->$c ?? 'DEFAULT' ;
EDIT: This only works for properties, not methods (as pointed out by "hackel" in the comments below)
Not until PHP 8.0.
This has been voted on and passed in the Nullsafe operator RFC.
The syntax will be ?->
.
So the statement:
if ($a && $a->$b && $a->$b->$c) {
$d = $a->$b->$c;
}
Could be rewritten to:
$d = $a?->$b?->$c; // If you are happy to assign null to $d upon failure
Or:
if ($a?->$b?->$c) {
$d = $a->$b->$c; // If you want to keep it exactly per the previous statement
}
The Nullsafe operator works for both properties and methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With