Nullable type hints

suggest change

Parameters

Nullable type hints were added in PHP 7.1 using a ? before the type.

function f(?string $a) {}
function g(string $a) {}

f(null); // valid
g(null); // TypeError: g(): Argument #1 ($a) must be of type string, null given

Before PHP 7.1, if a parameter has a type hint, it must declare a default value null to accept null values.

function f(string $a = null) {}
function g(string $a) {}

f(null); // valid
g(null); // TypeError: g(): Argument #1 ($a) must be of type string, null given

Return values

In PHP 7.0, functions with a return type must not return null.

In PHP 7.1, a function can declare a nullable return type. It must return a value of that type or null. Falling off the end of the function, or an empty return, is a TypeError.

function f() : ?string {
    return null;
}

function g() : ?string {}
function h() : ?string {}

f(); // OK
g(); // TypeError: g(): Return value must be of type ?string, none returned
h(); // TypeError: h(): Return value must be of type ?string, none returned

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents