Home > Backend Development > PHP Tutorial > How do PHP functions return NULL?

How do PHP functions return NULL?

PHPz
Release: 2024-04-12 11:33:02
Original
890 people have browsed it

PHP functions have two ways of returning NULL: explicitly returning null or returning no value. Returning null explicitly uses the return null statement, and if no value is returned, the function returns null by default.

PHP 函数如何返回 NULL?

#How do PHP functions return NULL?

NULL is a special value in PHP, which represents a null or unknown value. A function can return NULL by explicitly returning null or by returning no value (that is, by returning void).

Explicitly return NULL

The most direct way is to use the return statement to explicitly return null:

function getPhoneNumber(): ?string
{
    return null;
}
Copy after login

Added ? type hint to indicate that the function may return null.

Does not return any value

When the PHP function does not explicitly return any value, it returns null by default. For example:

function voidFunction(): void
{
    echo "This function doesn't return anything.";
}
Copy after login

Practical case

The following is an example of a function using NULL:

function getOptionalData(string $key): ?string
{
    $data = [
        'name' => 'John Doe',
        'age' => 30,
    ];

    return $data[$key] ?? null;
}

$name = getOptionalData('name'); // 返回 "John Doe"
$age = getOptionalData('age'); // 返回 30
$address = getOptionalData('address'); // 返回 NULL
Copy after login

In this function, if$key If is a valid key, the value in the associative array is returned; otherwise, null is returned.

The above is the detailed content of How do PHP functions return 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