rfc:nullable_return_types

This is an old revision of the document!


PHP RFC: Nullable Return Types

Introduction

PHP 7 introduced optional declaration of function return types.

function foo(): int {
}

However, it didn't make possible to mix declared return type with NULL. This leaded to inability to use return type declarations in many cases, like in the following example of binary-tree where the left and right nodes may be NULL by design.

class Node {
  private $left;
  private $right;

  function __construct(Node $left = null, Node $right = null) {
    $this->left = $left;
    $this->right = $right;
  }
  function getLeft() /* : Node */ {
    return $this->left;
  }
  function getRight() /* : Node */ {
    return $this->right;
  }
}

Proposal

I propose to use HHVM compatible syntax to declare nullable return types - ?<type>

So the previous example will look like the following:

class Node {
  private $left;
  private $right;

  function __construct(Node $left = null, Node $right = null) {
    $this->left = $left;
    $this->right = $right;
  }
  function getLeft(): ?Node {
    return $this->left;
  }
  function getRight(): ?Node {
    return $this->right;
  }
}

Usage of the same ?<type> syntax for arguments (and later properties) is not the subject of this RFC. Actually, arguments already may be declared as “nullable” using NULL default value (the same may be done for properties). This decision(s) may be done separately.

Backward Incompatible Changes

NONE

Proposed PHP Version(s)

This RFC targets PHP version 7.1.

Open Issues

NONE

Future Scope

Nullable Arguemnts without Default Values

This RFC doesn't propose any change to argument (or property) type declarations. The following code won't work, but this RFC doesn't prohibit to support this syntax later.

function foo(?int $a) {
}

Union Types

The "Union Types" RFC proposes different syntax, but misses implementation for more than a year. It provides smarter, but less usable (in my opinion) syntax.

function foo(): int|null {
}

Proposed Voting Choices

Simple “Yes/No” with a 2/3 majority to be accepted.

The vote will start on April 25 and finish on May 9.

Patches and Tests

Implementation

After the project is implemented, this section should contain

  1. the version(s) it was merged to
  2. a link to the git commit(s)
  3. a link to the PHP manual entry for the feature

References

rfc/nullable_return_types.1459958039.txt.gz · Last modified: 2017/09/22 13:28 (external edit)