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?
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?
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.
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)
In PHP versions less than 8, optional chaining isn't supported. You can emulate it for properties by using the error control operator (@
) which will suppress any errors that would normally occur from the assignment. For example:
$b = 'b';
$c = 'c';
$e = 'e';
$a = (object)['b' => (object)['e' => 2]];
@$d = $a->$b->$c;
var_dump($d);
@$d = $a->$b->$e;
var_dump($d);
Output:
NULL
int(2)
A better solution is to use the null coalescing operator as described in @FouedMOUSSI answer.
As of PHP8 (released 2020-11-26) optional chaining is supported via the nullsafe operator (see @Paul answer or the posted duplicate).
As mentioned by @Paul the nullsafe is available in PHP 8. After reading this question today I just realized PHP 8 was released yesterday (2020-11-26) with nullsafe operators available :)
So yes it is available in PHP now and I can't wait to use it.