1.2.295. Could Use Null-Safe Object Operator

When the preceding function call has the potential to return null, employing the null-safe object operator can help mitigate fatal errors.

One approach is to assess the returned value prior to utilization, ensuring it is not null, and refraining from invoking methods on a null reference. Alternatively, the null-safe operator can be employed, allowing verification of the end result. If the result is null, it indicates an error.

Another approach is to use the null-safe operator when the intermediate methods returns an object or a null. When chained, the null-safe operator will prevent Fatal Error.

<?php

// direct usage, with a check on the final value
$a = foo()?->b() ?? throw new exception('something went wrong when calculating $a');
   // throw as an expression is a PHP 8.0 code


// direct usage, may yield a Fatal error
foo()->b();

// indirect usage, with a check on the returned value
$a = foo();
$c = $a ? $a->b() : null;


function foo() : ?A {
    return rand(0, 1) ? new A() : null;
}

class A {
    function b() : string { return '';}
}

?>

See also PHP 8.0 feature focus: nullsafe methods and Nullsafe methods and properties.

1.2.295.1. Suggestions

  • Add a check on NULL before using the returned value

  • Update the previous method to prevent it from returning null

  • Use the null-safe object operator and test the result afterward

1.2.295.2. Specs

Short name

Structures/CouldUseNullableOperator

Rulesets

All, Suggestions

Exakat since

2.3.3

PHP Version

With PHP 8.0 and more recent

Severity

Major

Time To Fix

Slow (1 hour)

Precision

Medium

Features

nullsafe-object-operator, nullable

Available in

Entreprise Edition, Exakat Cloud