Reputation: 901
I want to get the value of a deeply nested property.
e.g.
$data->person->name->last_name;
The problem is I am not sure if person
or name
is declared. I also don't want to use nested if
statements. If
statements won't look good for deeply nested properties.
Is there a null-conditional operator in PHP?
Solved
There is no need for a null-conditional
operator since a null-coalescence
operator does the job.
Upvotes: 13
Views: 4348
Reputation: 2336
There is nullsafe operator since PHP 8.
$last_nam = $data?->person?->name?->last_name;
The advantage of nullsafe operator over null coalescing is that the former allows to specify exact parts of the chain that should be null-safe.
Upvotes: 10
Reputation: 1270
In PHP 7, a new feature, null coalescing operator (??) has been introduced. It is used to replace the ternary operation in conjunction with isset() function.
The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
For your example:
$username = isset($data->person->name) ? isset($data->person->last_name) : 'not name';
Upvotes: 1