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.
#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:
?type
Unlike using @
to suppress error messages. @
, ?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!