Skip to content

PHP Tutorial Functions

Return Types

Lesson 106 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

You can state what a function returns by writing a colon and a type after the brackets.

index.php
PHP
<?php
function fullName(string $first, string $last): string
{
    return $first . " " . $last;
}

echo fullName("Ada", "Lovelace");
Output
OUTPUT
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.

index.php
PHP
<?php
function logMessage(string $message): void
{
    echo "[LOG] " . $message . "\n";
}

logMessage("Saved");
Output
OUTPUT
[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.

index.php
PHP
<?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));
Output
OUTPUT
string(3) "Ben"
NULL

Union return types (PHP 8.0+)

index.php
PHP
<?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"));
Output
OUTPUT
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.

index.php
PHP
<?php
function fail(string $message): never
{
    throw new RuntimeException($message);
}

try {
    fail("Something broke");
} catch (RuntimeException $e) {
    echo $e->getMessage();
}
Output
OUTPUT
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 typeMeaning
: intAlways an integer
: ?stringA string or null
: int|stringEither type
: voidNothing
: neverDoes not return
: arrayAn array (list the item type in a comment)
info
Typed arrays
PHP cannot say “an array of strings” in a type. You say array and describe the items in a DocBlock, for example @return string[].