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
Release: 2024-12-15 12:39:11
Original
742 people have browsed it

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) {}
Copy after login
  • 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
Copy after login

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
}
Copy after login
  • 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
}
Copy after login
  • 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;
}
Copy after login
  • 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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template