Home > Article > Backend Development > How do PHP functions return NULL?
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.
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; }
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."; }
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
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!