You can state what a function returns by writing a colon and a type after the brackets.
<?php
function fullName(string $first, string $last): string
{
return $first . " " . $last;
}
echo fullName("Ada", "Lovelace");
Ada Lovelace
If the function returns something else, PHP throws a TypeError.
void: returns nothing
Use void for functions that do something but give nothing back.
<?php
function logMessage(string $message): void
{
echo "[LOG] " . $message . "\n";
}
logMessage("Saved");
[LOG] Saved
A void function must not return a value. You can write a plain return; to leave early.
Nullable return types
Use ? when a function might return null, for example when something is not found.
<?php
function findUser(array $users, int $id): ?string
{
return $users[$id] ?? null;
}
$users = [1 => "Ana", 2 => "Ben"];
var_dump(findUser($users, 2));
var_dump(findUser($users, 9));
string(3) "Ben"
NULL
Union return types (PHP 8.0+)
<?php
function parseNumber(string $text): int|float|null
{
if (!is_numeric($text)) {
return null;
}
return $text + 0;
}
var_dump(parseNumber("12"));
var_dump(parseNumber("1.5"));
var_dump(parseNumber("x"));
int(12)
float(1.5)
NULL
Unions are useful, but do not overuse them. A function that returns three unrelated types is hard to use.
bool and mixed
bool is common for checks: isValid(), hasAccess(). mixed means “anything” and tells the reader you did not narrow it down.
static and self in classes
Inside a class, static and self describe the class itself. They matter for chaining. You will use them in classes.
never (PHP 8.1+)
never means the function never comes back. It always throws an exception or ends the script.
<?php
function fail(string $message): never
{
throw new RuntimeException($message);
}
try {
fail("Something broke");
} catch (RuntimeException $e) {
echo $e->getMessage();
}
Something broke
Return type vs documentation
A return type is checked by PHP. A comment is not. When you can express it in a type, do so.
| Return type | Meaning |
|---|---|
: int | Always an integer |
: ?string | A string or null |
: int|string | Either type |
: void | Nothing |
: never | Does not return |
: array | An array (list the item type in a comment) |
Typed arrays
array and describe the items in a DocBlock, for example @return string[].