1.2.124. Check After Null Safe Operator

Null-safe operator is ?->, which prevents fatal errors in case the object of the call is NULL. The execution continues, though the result of the expression is now NULL too.

While it saves some checks in certain cases, the null-safe operator should be followed by a check on the returned value to process any misfire of the method.

This analysis checks that the result of the expression is collected, and compared to null.

<?php

$result = $object?->foo();

if ($result === null) {
     throw new ObjectException(The object could not call $foo\n);
}

?>

1.2.124.1. Suggestions

  • Collect and check the result of the expression to null

  • Remove the null-safe operator and check before calling the object’s method or property

1.2.124.2. Specs

Short name

Classes/CheckAfterNullSafeOperator

Rulesets

All, Analyze, Changed Behavior, Suggestions

Exakat since

2.6.4

PHP Version

With PHP 8.1 and more recent

Severity

Major

Time To Fix

Quick (30 mins)

Precision

High

Features

nullsafe-object-operator

Available in

Entreprise Edition, Exakat Cloud