Table of Contents

PHP RFC: Null Propagation Operator

Introduction

A common requirement in object-oriented programming is the need to check whether an object is NULL before attempting access its members. At present in PHP this must be done by breaking the statement into multiple parts, typically assigning the result of an expression to a variable and then branching with an if statement. This RFC proposes an operator that would allow such checks to be written inline.

The following code sample demonstrates the pattern that must currently be used:

class Foo {
    private $bar;
 
    public function __construct(?Bar $bar) {
        $this->bar = $bar;
    }
 
    public function getBar(): ?Bar {
        return $this->bar;
    }
}
 
$foo = new Foo(null);
$bar = $foo->getBar();
 
// We must check that $bar is not null before attempting access its members
if ($bar !== null) {
    $result = $bar->method();
} else {
    $result = null;
}

Proposal

This proposal allows a question mark ? to precede any object instance member access ->. This would cause the engine to check that the expression on the left of the member access does not evaluate to NULL, if it does then no error will be emitted, the remainder of the expression on the right will be short-circuited and the expression will evaluate to NULL. Using the same definitions from the Introduction:

$foo = new Foo(null);
$result = $foo->getBar()?->method();
var_dump($result); // NULL

This operator does not suppress any errors that are generated by the left hand side of the expression, it only short-circuits the right hand side.

Examples in other languages

Backward Incompatible Changes

None

Proposed PHP Version(s)

PHP 7.3

RFC Impact

To Opcache

TODO

Open Issues

Make sure there are no open issues when the vote starts!

Proposed Voting Choices

As this is a language change, a 2/3 majority is required.

Patches and Tests

TODO: Patch required

Implementation

TODO

References

Links to external references, discussions or RFCs