This is an old revision of the document!
PHP RFC: Null Propagation Operator
- Version: 0.1
- Date: 2018-01-23
- Author: Chris Wright, daverandom@php.net
- Status: Draft
- First Published at: https://wiki.php.net/rfc/null-propagation
Proposal
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; }
This proposal would allow 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
:
$foo = new Foo(null); $result = $foo->getBar()?->method(); var_dump($result); // NULL
Examples in other languages
- ECMA Script (Stage 1 proposal)
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