Home >Backend Development >PHP Tutorial >How Do Nullable Types Work in PHP7 and Beyond?

How Do Nullable Types Work in PHP7 and Beyond?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 09:59:14372browse

How Do Nullable Types Work in PHP7 and Beyond?

Nullable Types in PHP7: Understanding the Question Marks

PHP7 introduced the concept of nullable types, signified by the question mark (?) before a type declaration (?string, ?int). These types allow for a value to be either the specified type or null.

Parameters

When marking a parameter as nullable, it means that the function can accept either the specified type or null as an argument. For example:

public function (?string $parameter1, string $parameter2) {}

In this case, the function can receive either a string or null for $parameter1, but $parameter2 must be a string.

Return Type

Nullable types can also be used for return values. This indicates that the function can return either the specified type or null. For instance:

function error_func(): int {
    return null; // Invalid in PHP7.1+
}

function valid_func(): ?int {
    return null; // Valid in PHP7.1+
}

Property Type (PHP7.4 )

PHP7.4 introduced nullable types for property declarations. This allows a property to be either the specified type or null.

Nullable Union Types (PHP8 )

In PHP8, nullable types are shorthand for the union of the specified type and null. For example:

private ?object $bar = null; // PHP7.1+
private object|null $baz = null; // PHP8+

Error Handling

In PHP7.0 and earlier, using the question mark before a type declaration will result in a syntax error. PHP7.1 versions will accept nullable types.

References

  • [Nullable Types](https://www.php.net/manual/en/language.types.declarations.php#language.types.declarations.nullable)
  • [Class Properties Type Declarations](https://www.php.net/manual/en/language.oop5.properties.php#language.oop5.properties.declare)
  • [Nullable Union Type](https://wiki.php.net/rfc/union_types_v2)

The above is the detailed content of How Do Nullable Types Work in PHP7 and Beyond?. 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