ZetCode

PHP function Keyword

last modified November 25, 2026

The PHP function keyword declares a named function: a reusable block with parameters, an optional return type, and its own variable scope. Named functions are the basic building block of PHP programs and the reference point for closures and methods.

This article covers declarations, parameters, default values, return types, the void rule, nullable results, scope, recursion, and passing by reference. Anonymous functions and arrow functions have their own articles.

Basic definitions

The function keyword declares a named function. The declaration gives the function a name, a parameter list, an optional return type, and a body. Calling the name runs the body and returns a value, or null when the function has no return statement.

Function names are case-insensitive, so greet() and GREET() are the same function. A function declared at the top level belongs to the current namespace, which is the global namespace in a file without a namespace declaration. An unconditional declaration can be called from anywhere in the file, including before its declaration: PHP compiles the whole file before it runs it, so those functions are registered first.

A function cannot be declared twice, and PHP has no overloading by parameter types. Default values and nullable types cover most of the cases where another language would add an overload. The PHP functions tutorial covers the wider subject, including variable functions and first-class callables.

A first function

The first example declares a function after the call that uses it, then calls the same function with an upper-case name.

func_first.php
<?php

declare(strict_types=1);

echo greet("Alice"), "\n";

function greet(string $name): string
{
    return "Hello, $name!";
}

echo GREET("Bob"), "\n";

The call on the first line works because the declaration is unconditional and the file is compiled before execution. The parameter is typed string and the return type is string, so the function documents its contract. The second call with GREET shows that the name is case-insensitive, but mixed case still hurts readability; pick one spelling and keep it.

$ php func_first.php
Hello, Alice!
Hello, Bob!

Parameters and return types

A function may take several parameters, each with its own type, and return any declared type. The next example passes them by position and uses a default for an optional parameter.

func_params.php
<?php

declare(strict_types=1);

function rectangle(float $width, float $height): string
{
    $area = $width * $height;
    return "{$width}x{$height} = $area";
}

echo rectangle(3, 4), "\n";
echo rectangle(2.5, 4.0), "\n";

function describe(string $name, int $age, bool $active = true): string
{
    $status = $active ? "active" : "inactive";
    return "$name, $age, $status";
}

echo describe("Alice", 30), "\n";

rectangle(3, 4) passes integers to float parameters, which is allowed even under strict_types because integers widen to floats. The return type is string, and the body builds it with {$width}x{$height} so that the variable names are delimited clearly. Named arguments let the caller write describe(age: 30, name: "Alice") in any order; the named arguments article covers their rules.

$ php func_params.php
3x4 = 12
2.5x4 = 10
Alice, 30, active

Default parameter values

A parameter may declare a default value, which must be a constant expression. Parameters with defaults go after the required ones.

func_defaults.php
<?php

declare(strict_types=1);

const DEFAULT_RATE = 0.2;

function price(float $amount, float $rate = DEFAULT_RATE): float
{
    return $amount * (1 + $rate);
}

echo price(100), "\n";
echo price(100, 0.1), "\n";

function label(string $text, string $suffix = "!"): string
{
    return $text . $suffix;
}

echo label("Total"), "\n";
echo label("Total", "?"), "\n";

The default of $rate is the constant DEFAULT_RATE, evaluated when the function is called. price(100) uses it and price(100, 0.1) overrides it. The $suffix parameter shows a string default; passing "?" replaces it. A default does not make the parameter nullable: passing null explicitly still fails the type check unless the type is written as ?string.

$ php func_defaults.php
120
110
Total!
Total?

Return values and early exit

A function returns as soon as it reaches a return statement. Several returns are often clearer than one deeply nested condition.

func_return.php
<?php

declare(strict_types=1);

function category(int $age): string
{
    if ($age < 13) {
        return "child";
    }
    if ($age < 20) {
        return "teenager";
    }
    return "adult";
}

echo category(8), " ", category(15), " ", category(40), "\n";

function logMessage(string $message): void
{
    echo "[log] $message\n";
    return;
}

logMessage("ready");

category checks the smallest range first and returns immediately, so the remaining checks do not run. logMessage declares void, which means it returns nothing useful; a bare return; is still allowed to leave early. A function without any return statement also returns null, but declaring void documents the intent and lets PHP check it.

$ php func_return.php
child teenager adult
[log] ready

The void rule

A void function must not return a value. This is a compile-time rule, so the file is rejected before any line runs.

func_void_error.php
<?php

declare(strict_types=1);

function logMessage(string $message): void
{
    return $message;
}

echo logMessage("ready");

The parser reports A void function must not return a value at the return statement. Remove the value and keep return;, or change the return type to the type of the value. The same rule applies to methods declared void.

$ php func_void_error.php
Fatal error: A void function must not return a value in /app/func_void_error.php on line 7
Stack trace:
#0 {main}

Nullable return types

A question mark before a type means the value may also be null. This is the usual way for a lookup function to report that nothing was found.

func_nullable.php
<?php

declare(strict_types=1);

function findUser(array $users, string $name): ?array
{
    foreach ($users as $user) {
        if ($user['name'] === $name) {
            return $user;
        }
    }
    return null;
}

$users = [
    ['name' => 'Alice', 'age' => 30],
    ['name' => 'Bob', 'age' => 25],
];

$user = findUser($users, "Alice");

if ($user !== null) {
    echo $user['name'], " is ", $user['age'], "\n";
}

var_dump(findUser($users, "Carol"));

findUser returns the matching row or null, and the caller checks with !== null before reading fields. A nullable return type forces that check to be explicit; without it, the caller could treat null as an array and get an error later. The output shows a found user and a NULL result for a name that is not in the list.

$ php func_nullable.php
Alice is 30
NULL

Variable scope

A function has its own variable scope. It sees its parameters and the variables it creates, but not the variables of the file that called it.

func_scope.php
<?php

declare(strict_types=1);

$total = 5;

function readTotal()
{
    return $total;
}

$value = readTotal();
var_dump($value);

function localCopy(): int
{
    $total = 100;
    return $total;
}

echo localCopy(), " ", $total, "\n";

readTotal tries to read $total from the outer scope, but the name is undefined inside the function. PHP raises a warning, evaluates the missing variable as null, and continues. The assignment in localCopy creates a separate local variable, so the outer $total stays 5. To read or change a global variable, a function has to declare it with global, which is the subject of the global keyword article.

$ php func_scope.php
Warning: Undefined variable $total in /app/func_scope.php on line 9
NULL
100 5

Recursion

A function may call itself. Every recursive function needs a base case that stops the calls, or the stack grows until PHP runs out of memory.

func_recursion.php
<?php

declare(strict_types=1);

function factorial(int $n): int
{
    if ($n <= 1) {
        return 1;
    }
    return $n * factorial($n - 1);
}

function fib(int $n): int
{
    if ($n < 2) {
        return $n;
    }
    return fib($n - 1) + fib($n - 2);
}

echo factorial(10), "\n";
echo fib(10), "\n";
echo factorial(3), "\n";

factorial multiplies $n by the factorial of $n - 1 until $n is 1. fib has two recursive calls and recomputes many values, which is fine for 10 but grows exponentially. factorial(21) would exceed the integer range, become a float, and fail the int return type; keep recursive results within the type's range or use a wider representation.

$ php func_recursion.php
3628800
55
6

Passing by reference

By default, a function receives a copy of each argument. An ampersand before the parameter makes it a reference to the caller's variable, so the function can change it.

func_reference.php
<?php

declare(strict_types=1);

function addItem(array &$items, string $item): int
{
    $items[] = $item;
    return count($items);
}

function addZero(int $number): void
{
    $number = 0;
}

$cart = ["apple"];
echo addItem($cart, "pear"), "\n";
print_r($cart);

$count = 3;
addZero($count);
echo $count, "\n";

addItem appends to the caller's array because &$items is a reference; the returned count is 2 and the printed array contains both fruits. addZero takes its integer by value, so setting $number to 0 changes only the local copy and $count stays 3. Reference parameters are useful for accumulating results, but a function that returns a new array is easier to follow; prefer the return value unless the copy is expensive or the change is the point.

$ php func_reference.php
2
Array
(
    [0] => apple
    [1] => pear
)
3

Best practices

A good function has one job, a clear name, and a contract that its signature states.

Source

PHP manual: user-defined functions

PHP manual: function arguments

PHP manual: return values

PHP manual: variable scope

This article covered the PHP function keyword: declarations, typed parameters, defaults, returns, scope, recursion, and references. Continue with PHP global keyword for scope across functions, or read PHP functions for the full tutorial.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all PHP tutorials.