Nullable type hints

suggest change

Parameters

Nullable type hint was added in PHP 7.1 using the ? operator before the type hint.

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

f(null); // valid
g(null); // TypeError: Argument 1 passed to g() must be of the 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: Argument 1 passed to g() must be of the type string, null given

Return values

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

In PHP 7.1, functions can declare a nullable return type hint. However, the function must still return null, not void (no/empty return statements).

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

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

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

Feedback about page:

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



Table Of Contents