PHP8’s Nullsafe Operator or “Optional Chaining”
In JavaScript this feature is called “optional chaining” where you can reduce the amount of checks that you need to do by chaining accessors with a ?.
For example const street = User.address?.street
if address is null, street will be null.
PHP has taken note and added a similar feature called the Nullsafe Operator. The nullsafe operator is denoted by `?->` and can significantly reduce the amount of boilerplate code and null checks required in your PHP applications.
1. Accessing object properties
Let’s start with a simple example of accessing object properties. Without the nullsafe operator, you would typically have to check for null objects before accessing their properties, like this:
class User {
public $address;
}
$user = new User();
$street = $user->address ? $user->address->street : null;
With the nullsafe operator, the code becomes cleaner and easier to read:
$street = $user?->address?->street;
If the $user or $address object is null, $street will be set to null without throwing an error.
2. Calling object methods
Similarly, you can use the nullsafe operator when calling object methods. For instance, consider this example:
class User {
public function getAddress() {
// code to get the address
}
}
$user = new User();
$address = $user ? $user->getAddress() : null;
Using the nullsafe operator, this code becomes:
$address = $user?->getAddress();
If $user is null, $address will be set to null, and no error will be thrown.
3. Chaining multiple nullsafe operators
The nullsafe operator can be chained, making it easier to handle deeply nested properties or method calls. Here’s an example:
class User {
public function getCompany() {
// code to get the company
}
}
class Company {
public function getDepartment() {
// code to get the department
}
}
$user = new User();
$department = $user?->getCompany()?->getDepartment();
If either $user or the company object is null, $department will be set to null without any errors.
4. Combining nullsafe and normal operators
You can combine the nullsafe operator with other operators like ‘->’ and ‘::’ in your code. Here’s an example:
class User {
public static function find($id) {
// code to find the user
}
}
class Company {
public function getDepartment() {
// code to get the department
}
}
$userId = 1;
$department = User::find($userId)?->getCompany()?->getDepartment();
In this example, the static method ‘find’ is called with the normal ‘::’ operator, while the nullsafe operator is used for the subsequent method calls.
PHP 8’s nullsafe operator offers a clean and efficient way to handle null values when accessing object properties and calling methods. It reduces boilerplate code and helps make your PHP applications more readable and maintainable. As you refactor your existing code or start new projects, consider leveraging the nullsafe operator to streamline your code and reduce the number of null checks required.