Home > Backend Development > PHP Tutorial > Can the type of PHP function return value be null?

Can the type of PHP function return value be null?

WBOY
Release: 2024-04-12 10:12:02
Original
1221 people have browsed it

The return value of a PHP function can be null. Explicitly declaring the return value type as ?type can indicate that the function can return null or a value of a specific type.

PHP 函数返回值的类型是否可以为 null?

#Can the type of the return value of a PHP function be null?

When a function does not explicitly return any value, PHP will implicitly return NULL. However, starting with PHP 7.0, you can explicitly declare a function's return type as ?type, indicating that the function can return NULL or a value of the given type.

Syntax:

function functionName(): ?type {
    // ...
}
Copy after login

Notes:

  • Declare the return value type as ?type Unlike using @ to suppress error messages.
  • IDEs (such as PHPStorm) will display type hints based on your declarations.
  • Unlike @, ?type allows you to take advantage of the benefits of type hints while still allowing functions to return NULL.

Practical case:

function getUserName(int $userId): ?string
{
    // ...

    if ($user === null) {
        return null;
    }

    return $user->name;
}
Copy after login

In this example, the getUserName function declares that it accepts an integer $userId Parameters and returns an optional string, i.e. ?string. If the user is not found, the function returns NULL.

Conclusion:

Using ?type in PHP to declare the return value type of a function can ensure code security and maintainability. Also allows functions to return NULL.

The above is the detailed content of Can the type of PHP function return value be null?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template