Null is a type that has only one possible value null
. The null
value indicates that the variable doesn't have a value. However, due to null
value, we might need to write more code for additional checks. It is very common that an expression can return an object or null
value. In this case, if we want to call a method on an object or access an object property, we need to check that a value is not null
.
Let's say we have Auth
, User
and Address
classes:
<?php
class Auth
{
public static function user(): ?User
{
return null;
}
}
<?php
class User
{
public function getAddress(): ?Address
{
return null;
}
}
<?php
class Address
{
public ?string $city = null;
}
In versions prior to PHP 8.0, in order to get a value of the city
property, we can write the following code:
<?php
require_once 'Address.php';
require_once 'User.php';
require_once 'Auth.php';
$city = null;
$user = Auth::user();
if ($user !== null) {
$address = $user->getAddress();
if ($address !== null) {
$city = $address->city;
}
}
Since PHP 8.0, we can use nullsafe operator (?->
). This operator can be used to call a method on an object or access an object property same as ->
operator. However, nullsafe operator returns null
value if an object is null
instead of throwing an exception. The nullsafe operator immediately returns null
if the left side of the operator evaluates to null
, without executing the entire chain.
In PHP 8.0 or newer versions, we can rewrite the previous code as follows:
<?php
require_once 'Address.php';
require_once 'User.php';
require_once 'Auth.php';
$city = Auth::user()?->getAddress()?->city;
There are some notes for nullsafe operator:
- Nullsafe operator cannot be used in write context. For example, we cannot use this operator to assign a value to a property.
<?php
require_once 'Address.php';
require_once 'User.php';
$user = new User();
$user->getAddress()?->city = 'Washington';
Fatal error: Can't use nullsafe operator in write context in main.php on line 7
- Nullsafe operator cannot be used with reference.
<?php
require_once 'Address.php';
require_once 'User.php';
$user = new User();
$city = &$user->getAddress()?->city;
Fatal error: Cannot take reference of a nullsafe chain in main.php on line 7
Leave a Comment
Cancel reply