Home >Backend Development >PHP Tutorial >How Do Nullable Types Work in PHP 7 and Above?

How Do Nullable Types Work in PHP 7 and Above?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 12:39:11844browse

How Do Nullable Types Work in PHP 7 and Above?

Understanding PHP 7's Nullable Types (?string or ?int)

In PHP 7, a new feature known as "nullable types" was introduced. It allows developers to specify that a parameter or return value can be either the specified type or null. Nullable types are denoted by a question mark (?) placed before the type declaration.

Nullable Types in Parameters

Syntax:

function test(?string $parameter1, string $parameter2) {}
  • Parameters marked as nullable (?string) can accept both strings and null values.
  • Parameters without nullable types (string) must receive a non-null value or an error will be thrown.

Example:

test("foo", "bar"); // OK
test(null, "foo"); // OK
test("foo", null); // Error

Nullable Types in Return Values

Syntax:

function error_func(): int {
    return null ; // Error: Return value must be of type integer
}

function valid_func(): ?int {
    return null ; // OK
}
  • Functions with nullable return types can return either the specified type or null.
  • Functions without nullable return types must return non-null values or an error will be thrown.

Nullable Types in Properties (PHP 7.4 )

Syntax:

class Foo
{
    private ?object $bar = null; // OK: can be null
}
  • Class properties can have nullable types, indicating that they can contain null values.

Nullable Union Types (PHP 8.0 )

As of PHP 8.0, "?T notation is considered a shorthand for the common case of T|null".

Syntax:

class Foo
{
    private object|null $baz = null;
}
  • Nullable union types allow variables to be assigned either the specified type or null.

Error Handling

If the PHP version used is lower than 7.1, a syntax error will be thrown if nullable types are used. In such cases, remove the question mark (?).

References

  • Nullable Type (PHP 7.1 ):
  • Class Properties Type Declarations (PHP 7.4 ):
  • Nullable Union Type (PHP 8.0 ):

The above is the detailed content of How Do Nullable Types Work in PHP 7 and Above?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn