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

Can the type of PHP function return value be null?

WBOY
WBOYOriginal
2024-04-12 10:12:021151browse

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 {
    // ...
}

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;
}

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!

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