Small pieces with clear contracts
A function gives a name to a piece of work and a contract to the rest of the program: give me these inputs, and I will give you back that. Good PHP code is mostly small functions and methods with clear contracts, and modern PHP lets you write a large part of the contract into the code itself, as types that the engine checks on every call.
PHP also ships with thousands of built-in functions, from strlen to array_map to password_hash. They grew over three decades, so their names and argument orders are not always consistent: str_replace($search, $replace, $subject) puts the text last, strpos($haystack, $needle) puts it first, and some names have underscores (str_contains) while older ones do not (strtolower). Every PHP programmer keeps the manual open. Named arguments, which you will meet below, help a great deal: str_pad($s, length: 10, pad_type: STR_PAD_LEFT) says what each argument means.
This lesson covers how to write your own functions well: types, the various ways to pass arguments, scope, functions as values, and recursion.
Declaring a function
function name(Type $param, Type $other = defaultValue): ReturnType
{
// body
return $value;
}Function names are case-insensitive (but always call a function exactly as it was declared), and a function can be called before its declaration in the same file. Types are optional, but in modern code every parameter and every return value has one. These are the type forms you will write:
| Form | Meaning | Since |
|---|---|---|
int, string, array, Foo … | exactly that type (or a subclass) | 7.0 for scalars |
?string | string or null | 7.1 |
int|float | a union: any of the listed types | 8.0 |
mixed | anything at all, including null | 8.0 |
void | returns nothing (return type only) | 7.1 |
never | never returns: always throws or exits (return type only) | 8.1 |
static | the class of the object it was called on (methods only) | 8.0 |
A&B | an intersection: an object that is both | 8.1 |
(A&B)|null | disjunctive normal form, mixing the two | 8.2 |
Arrays are typed only as array; PHP has no built-in way to say "array of integers". Teams write that in a docblock comment, @param list<int> $ids or @return array<string, float>, and static analysers (PHPStan, Psalm) check it. You will see these comments in nearly every professional codebase.
Defaults, named arguments and nullable parameters
<?php
declare(strict_types=1);
function formatPrice(int $cents, string $currency = "EUR", bool $withSymbol = true): string
{
$symbols = ["EUR" => "€", "USD" => "US$", "INR" => "₹", "NGN" => "₦"];
$amount = number_format($cents / 100, 2);
if (!$withSymbol) {
return "$amount $currency";
}
return ($symbols[$currency] ?? "$currency ") . $amount;
}
function initials(string $given, ?string $family = null): string
{
return $family === null ? $given[0] : $given[0] . $family[0];
}
function half(int|float $x): float
{
return $x / 2;
}
echo formatPrice(123456), "\n";
echo formatPrice(999, "INR"), "\n";
echo formatPrice(250000, withSymbol: false, currency: "NGN"), "\n";
echo formatPrice(4200, "CHF"), "\n";
echo initials("Kwame", "Mensah"), " ", initials("Aiko"), "\n";
var_dump(half(5), half(2.5));
try {
echo formatPrice(100, withSymbol: false, colour: "red"), "\n";
} catch (Error $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}€1,234.56
₹9.99
2,500.00 NGN
CHF 42.00
KM A
float(2.5)
float(1.25)
Error: Unknown named parameter $colourNotice what the named arguments in the third call buy you: you can skip $currency's position, pass the arguments in any order, and a reader sees what false means without opening the function. Misspell a name and PHP refuses with an Error, as the last call shows. The flip side is that parameter names are now part of your function's public contract: renaming $withSymbol breaks every caller who used the name. Library authors think about that before they rename.
?string $family = null is the standard way to make a parameter optional when "not given" is a meaningful state. Write the ? explicitly: since PHP 8.4, giving a non-nullable type a default of null (string $family = null) is deprecated.
The union int|float accepts either; with strict types on, it still refuses a numeric string.
Variadics, spreading and references
A parameter written ...$values collects all remaining arguments into an array. The same three dots at a call site spread an array into separate arguments; when the array has string keys, they become named arguments (PHP 8.1).
<?php
declare(strict_types=1);
function average(float ...$values): float
{
return $values === [] ? 0.0 : array_sum($values) / count($values);
}
function addTax(float &$price, float $rate): void
{
$price = round($price * (1 + $rate), 2);
}
function describeTrip(string $from, string $to, int $days = 1): string
{
return "$from → $to, $days day" . ($days === 1 ? "" : "s");
}
echo average(3, 4, 5), "\n";
$scores = [90, 72.5, 88];
echo average(...$scores), "\n";
echo average(), "\n";
$price = 100.0;
addTax($price, 0.16);
echo $price, "\n";
$trip = ["to" => "Cusco", "from" => "Lima", "days" => 4];
echo describeTrip(...$trip), "\n"; // string keys become named arguments
echo describeTrip("Oslo", ...["to" => "Bergen"]), "\n";4
83.5
0
116
Lima → Cusco, 4 days
Oslo → Bergen, 1 dayTwo small things in the output: echo prints the float 4.0 as 4 and 0.0 as 0, so if you need a fixed format, use number_format or printf. And average(3, 4, 5) is allowed in strict mode because an int may always widen to a float.
Passing by value and by reference. Normally a function receives a copy of each argument: changing the parameter inside the function does not change the caller's variable. That holds for arrays too, which surprises people coming from Python or JavaScript. PHP makes it cheap with copy-on-write: the array is only really copied if the function modifies it. Objects behave differently: the variable holds a handle to the object, and the function receives a copy of the handle, so it can change the object's properties. You will see this in the lesson on classes.
An & before a parameter, as in addTax(float &$price, …), passes the caller's variable itself, so the function can change it. The built-in sort($array) works that way. In your own code, prefer returning a new value: $price = withTax($price, 0.16) is easier to read, test and reason about than a function that reaches back into its caller's variables.
Scope. A function sees only its parameters and the variables it creates. Variables from the surrounding file are not visible inside, unlike in many languages. There is a global keyword to reach them, and you should almost never use it: pass what the function needs as arguments.
Functions as values
A closure is a function without a name, stored in a variable or passed to another function. Because PHP functions cannot see outer variables, a closure must say which ones it wants with use. By default use ($x) copies the value at the moment the closure is created; use (&$x) shares the variable itself.
An arrow function (PHP 7.4), written fn(params) => expression, is a closure whose body is a single expression. It captures any outer variable it mentions automatically, by value, when it is created. Arrow functions are what you will pass to array_map, array_filter and usort most of the time.
The program below shows these, plus four more tools: first-class callable syntax, the pipe operator, partial application and static variables.
<?php
declare(strict_types=1);
// A closure that remembers state through a captured reference.
function makeCounter(): Closure
{
$count = 0;
return function () use (&$count): int {
return ++$count;
};
}
$tick = makeCounter();
$tick();
$tick();
echo "counter: ", $tick(), "\n";
// An arrow function captures outer variables by value, when it is created.
$rate = 0.2;
$withVat = fn(float $net): float => round($net * (1 + $rate), 2);
$rate = 0.5;
echo "with VAT: ", $withVat(10.0), "\n";
// First-class callable syntax turns any function into a Closure.
$lengths = array_map(strlen(...), ["Accra", "Lima", "Hanoi"]);
echo "lengths: ", implode(", ", $lengths), "\n";
// The pipe operator (PHP 8.5) passes a value through one callable after another.
$slug = " Learning PHP: Functions & Closures "
|> trim(...)
|> strtolower(...)
|> (fn(string $s): string => preg_replace('/[^a-z0-9]+/', '-', $s))
|> (fn(string $s): string => trim($s, '-'));
echo "slug: $slug\n";
// Partial function application (PHP 8.6): ? marks the arguments still to come.
$twoPlaces = round(?, 2);
$dashes = str_replace(" ", "-", ?);
echo "partial: ", $twoPlaces(3.14159), " ", $dashes("a b c"), "\n";
// A static variable keeps its value between calls of the same function.
function nextTicket(): string
{
static $n = 0;
$n++;
return sprintf("T-%03d", $n);
}
echo nextTicket(), " ", nextTicket(), " ", nextTicket(), "\n";counter: 3
with VAT: 12
lengths: 5, 4, 5
slug: learning-php-functions-closures
partial: 3.14 a-b-c
T-001 T-002 T-003Walk through it:
- The counter. Each call to
makeCounter()creates a fresh$countand a closure that shares it by reference. The third call returns 3. Each counter you make has its own$count. - The arrow function saw
$rateas 0.2 when it was created; changing$rateto 0.5 afterwards did not affect it. So the result is 10 × 1.2 = 12. This "captured at creation" rule is the most common closure surprise in PHP. strlen(...)(PHP 8.1) is first-class callable syntax: the literal...means "don't call it; give me the function as aClosure". It works for methods too, as$obj->method(...)andFoo::bar(...). The older way, passing the string'strlen', still works, but it hides the function from your editor and static analyser.- The pipe operator
|>(PHP 8.5) takes the value on its left and passes it as the single argument of the callable on its right. A chain of pipes reads top to bottom in the order things happen, instead of inside out (trim(strtolower(trim(...)))). An arrow function used in a pipe must be wrapped in parentheses. - Partial application (PHP 8.6): writing
?in place of an argument does not call the function; it creates a closure that waits for the missing arguments.round(?, 2)is "round to two places", ready to use witharray_mapor a pipe. If you need to support PHP 8.5 or earlier, writefn($x) => round($x, 2)instead. - A static variable is initialised once and keeps its value between calls. It is handy for a cache inside a function, but it is hidden global state, so use it sparingly.
Recursion over nested data
A function may call itself. Recursion is the natural way to walk data that nests to any depth, such as a category tree, a parsed JSON document or a folder structure:
<?php
declare(strict_types=1);
/**
* @param array<string, array> $tree category name => subcategories
*/
function render(array $tree, int $depth = 0): void
{
foreach ($tree as $name => $children) {
echo str_repeat(" ", $depth), "- ", $name, "\n";
render($children, $depth + 1);
}
}
/** @param array<string, array> $tree */
function countLeaves(array $tree): int
{
$total = 0;
foreach ($tree as $children) {
$total += $children === [] ? 1 : countLeaves($children);
}
return $total;
}
$catalogue = [
"Food" => [
"Grains" => ["Rice" => [], "Teff" => [], "Quinoa" => []],
"Spices" => ["Berbere" => [], "Garam masala" => []],
],
"Books" => [
"Fiction" => [],
"Science" => ["Physics" => [], "Biology" => []],
],
];
render($catalogue);
echo "Leaf categories: ", countLeaves($catalogue), "\n";- Food
- Grains
- Rice
- Teff
- Quinoa
- Spices
- Berbere
- Garam masala
- Books
- Fiction
- Science
- Physics
- Biology
Leaf categories: 8Each call handles one level and hands the rest to a smaller call; an empty array is the base case. PHP does not optimise tail calls, and every level of recursion costs memory. When we tried a simple recursive function a million levels deep with the default 128 MB memory_limit, the script died after about 330,000 levels with a fatal "Allowed memory size exhausted" error, which cannot be caught. For trees of normal depth, recursion is clear and fine; for long linear chains, use a loop.
Generators: functions that produce values one at a time
A function that contains the keyword yield is a generator function. Calling it does not run its body. It returns a Generator object, and the body runs only as far as the next yield each time a loop asks for another value. Between requests, the function is paused with all its local variables intact.
This gives you two things. You can describe sequences that are long or even endless without building them in memory, and you can write a processing step (read, clean, filter) as a simple loop that hands values onward instead of collecting them into an array first.
<?php
declare(strict_types=1);
/** @return Generator<int, int> an endless sequence */
function fibonacci(): Generator
{
[$a, $b] = [0, 1];
while (true) {
yield $a;
[$a, $b] = [$b, $a + $b];
}
}
/**
* @param iterable<int, string> $lines
* @return Generator<int, string> line number => content
*/
function meaningfulLines(iterable $lines): Generator
{
foreach ($lines as $index => $line) {
$line = trim($line);
if ($line !== "" && !str_starts_with($line, "#")) {
yield $index + 1 => $line;
}
}
}
/** @return Generator<int, int> */
function take(iterable $items, int $n): Generator
{
if ($n <= 0) {
return;
}
foreach ($items as $key => $item) {
yield $key => $item;
if (--$n === 0) {
return;
}
}
}
echo implode(" ", iterator_to_array(take(fibonacci(), 12))), "\n";
$config = ["# settings", "host = example.org", "", "port = 8080", " # end"];
foreach (meaningfulLines($config) as $lineNo => $line) {
echo "line $lineNo: $line\n";
}
$gen = meaningfulLines($config);
echo get_debug_type($gen), ", first value: ", $gen->current(), "\n";0 1 1 2 3 5 8 13 21 34 55 89
line 2: host = example.org
line 4: port = 8080
Generator, first value: host = example.orgfibonacci() has a while (true) loop and would never finish if it were an ordinary function. As a generator it is harmless: take asks it for exactly twelve values and then stops asking. yield $key => $value produces a key as well as a value, which is how meaningfulLines reports the original line numbers. iterator_to_array collects whatever a generator produces into an ordinary array, when you do want one.
Generators are the standard way to read large files line by line or page through database results without loading everything at once: a function that yields one row at a time uses the same small amount of memory whether the file has a hundred lines or ten million. yield from other() delegates to another generator. Parameters typed iterable accept both arrays and generators, so the same function can process either.
Common misunderstandings
Misconception
"Passing an array to a function lets the function change it." Arrays are passed by value. The function works on its own copy (made lazily, only if it writes), and the caller's array is unchanged. Return the new array, or, if you truly must, take it by reference with &.
Misconception
"A closure sees the current value of the variables it uses." use ($x) and arrow functions copy the value when the closure is created. Only use (&$x) shares the variable. If a callback prints a stale value, this is almost always why.
Misconception
"Variables defined at the top of the file are available inside functions." They are not; PHP functions have their own scope. This is a deliberate design that keeps functions independent. Pass values in as parameters.
Misconception
"void and never mean the same thing." A void function returns normally, just without a value. A never function does not return at all: it always throws an exception or ends the script, like function fail(string $why): never { throw new RuntimeException($why); }. Static analysers use never to know that code after the call is unreachable.
Misconception
"Calling a generator function runs it." It only creates the Generator object; the body has not started. If a generator is supposed to write a log line or throw on bad input, nothing happens until someone iterates over it. A generator that nobody iterates never runs at all, which can hide bugs in tests that only check the return type.
Note
How professionals write PHP functions. Type every parameter and return value, and add a docblock only for what types cannot say (the element types of arrays, the meaning of a return value). Keep functions short enough to read without scrolling. Prefer returning new values to modifying arguments by reference. Avoid global and keep static variables rare. Pass collaborators in as arguments rather than reaching for them. Functions written this way are easy to test, which the later lessons will put to use.
Exercises
1. Functions
Warm-upComputationalWhat does this program print?
<?php
$x = 1;
$f = fn() => $x * 10;
$x = 5;
echo $f(), "\n";
2. Functions
Warm-upComputationalWhat does this program print?
<?php
declare(strict_types=1);
function addItem(array $list, string $item): array
{
$list[] = $item;
return $list;
}
$a = ["tea"];
$b = addItem($a, "rice");
echo count($a), count($b), "\n";
3. Functions
CoreComputationalUsing the makeCounter function from the lesson (each call returns a closure that increments and returns its own $count, captured by reference), what does this print?
$c1 = makeCounter();
$c2 = makeCounter();
$c1();
$c1();
$c2();
echo $c1() + $c2(), "\n";
4. Functions
CoreComputationalWhat does this line print (PHP 8.5 or later)?
echo " Hello " |> trim(...) |> strrev(...) |> strtoupper(...), "\n";
5. Functions
CoreComputationalWhat does this program print?
<?php
function f(int $n): int
{
return $n <= 1 ? 1 : f($n - 1) + f($n - 2);
}
echo f(6), "\n";
6. Functions
CoreComputationalWhat does this program print?
<?php
function joinAll(string $sep, string ...$parts): string
{
return implode($sep, $parts);
}
echo joinAll("-", ...["a", "b"], ...["c"]), "\n";
7. Functions
CoreComputationalGiven function f($a, $b, $c) { return "$a$b$c"; }, which call is an error?
8. Functions
StretchHumanA function abort(int $status, string $message) sends an error page and then always calls exit. Which return type describes it best?
Further reading and resources
- PHP Manual: FunctionsUser-defined functions, arguments, return values and variable functions.
- PHP Manual: Function argumentsDefaults, references, variadics and named arguments.
- PHP Manual: Arrow functionsThe fn syntax and its automatic by-value capture.
- PHP Manual: First class callable syntaxTurning any function or method into a Closure with (...).
- PHP Manual: Type declarationsEvery type you can write on a parameter, property or return value.