Is there optional chaining 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.
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)
Demo on 3v4l.org
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).
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)