Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there optional chaining in PHP? [duplicate]

Tags:

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?

like image 464
Chris Jung Avatar asked Sep 06 '19 08:09

Chris Jung


2 Answers

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)

like image 111
Foued MOUSSI Avatar answered Sep 17 '22 20:09

Foued MOUSSI


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.

like image 37
Paul Avatar answered Sep 16 '22 20:09

Paul