PHP8 Null safe operator

PHP 8.0 introduces a new syntax, the null-safe operator, which adds the optional chaining capability.

If you have a groovy background Null-safe operator analogous to Safe Navigation Operator in groovy, while the access operator precedes the null-safe operator in groovy .? it’s the other way around in php ?->

In Groovy

1
obj.?aMethod().?aPropty

In PHP 8.0

1
$obj?->aMethod()?->aPropty;

If the left-hand expression evaluates to null, the null safe operator silently returns null.

In the below example, we’re checking whether the username is ‘admin’ but first we need to see if the user is signed in otherwise, PHP will throw an error.

In PHP 7, the code may look like this

1
2
3
4
5
6
7
if (auth()->user() !== null) {
	abort(Response::HTTP_FORBIDDEN)
}

if (auth()->user()->username !== 'admin') {
	abort(Response::HTTP_FORBIDDEN)
}

Starting with PHP 8, we can leverage the Null-safe operator to have cleaner concise code.

1
2
3
if (auth()->user()?->username !== 'admin') {
	abort(Response::HTTP_FORBIDDEN)
}
updatedupdated2024-01-172024-01-17