Functions

Introduction

As programs grow, you do not want to copy the same lines again and again. A function is a named block of code that you can run whenever you need it. It can take values in, called parameters, and give a value back with return. Functions make programs shorter, easier to test and easier to read, because a good name such as square explains what a block of code does. PHP already has hundreds of built-in functions, such as strlen and count, and now you will write your own.

How it works

You define a function with the keyword function, a name, parameters in brackets and a body in braces:

function square(int $n): int {
    return $n * $n;
}
echo square(7);

The words int before $n and after the brackets are type declarations. They say that the parameter is an int and the result is an int. They are optional, but they catch mistakes early, and good PHP code uses them. Use void when a function returns nothing, and ?string when it may also return null. A function ends when it reaches return.

A parameter can have a default value: function greet(string $name, string $greeting = "Hello"). When the caller leaves it out, the default is used. In PHP 8 you can also pass named arguments: describe(age: 30, name: "Bo"). The order no longer matters, and the call explains itself.

A function can return only one value, but that value can be an array. The caller can unpack it with [$lo, $hi] = minMax($values);. A variadic parameter, written int ...$nums, collects any number of arguments into an array.

By default PHP passes a copy of each value, so changing a parameter inside the function does not change the variable outside. If you want the function to change the original, put an ampersand before the parameter: function increment(int &$n). This is called passing by reference; use it rarely.

A function can call itself. This is recursion. The function fact calls fact($n - 1) until $n is 1. Every recursive function needs a base case that stops the calls, otherwise it never ends. For deep problems, loops are usually faster and safer.

Finally, give each function one clear job. If you can say what it does in one short sentence without the word "and", the size is right. Name it with a verb, such as calculateTotal or isPrime.

Example

<?php
function square(int $n): int
{
    return $n * $n;
}

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

function minMax(array $values): array
{
    return [min($values), max($values)];
}

function increment(int &$n): void
{
    $n++;
}

function total(int ...$nums): int
{
    return array_sum($nums);
}

function describe(string $name, int $age): string
{
    return "$name is $age";
}

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

echo square(7), "\n";
echo greet("Ada"), "\n";
echo greet("Ada", "Hi"), "\n";
[$lo, $hi] = minMax([4, 9, 2, 7]);
echo "$lo $hi\n";
$x = 5;
increment($x);
echo $x, "\n";
echo total(1, 2, 3, 4), "\n";
echo describe(age: 30, name: "Bo"), "\n";
echo fact(10), "\n";

Line by line

  1. square takes an int and returns an int.
  2. greet has a default parameter. It is called with one argument and with two.
  3. minMax returns an array of two values, and [$lo, $hi] unpacks them.
  4. increment receives $x by reference, so $x becomes 6 outside.
  5. total is variadic and adds up any number of values.
  6. describe is called with named arguments in a different order.
  7. fact calls itself and stops at the base case of 1.

Expected result

49
Hello, Ada!
Hi, Ada!
2 9
6
10
Bo is 30
3628800

In the real world

Every large program is built from small functions. A web shop has functions to calculate tax, check a coupon, format a price and send an email. Teams write tests for each function, because a function with clear inputs and outputs is easy to test. Libraries are simply collections of functions that other people wrote.

Common mistakes

  • Forgetting return, so the function gives null.
  • Printing with echo inside a function when the caller wants the value.
  • Recursion without a base case, which never stops.
  • Expecting a parameter to change the outside variable without using a reference.

Best practices

  • Give each function one job and a verb name.
  • Use type declarations for parameters and results.
  • Return values instead of printing inside the function.
  • Keep functions short; split them when they grow.

Summary

A function is a named block with parameters and a return value. Add types, default values and named arguments to make calls clear. Use ... for any number of arguments, & to change the caller's variable, and recursion with a base case when a problem repeats itself in a smaller form.

Quick check

1. What does a function return when it has no return statement?
2. What does the & before a parameter mean?
3. Which call uses a named argument?
4. What must every recursive function have?

Key takeaways

  • A function has a name, parameters and a return value.
  • Types, defaults and named arguments make calls safe and clear.
  • Recursion needs a base case.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.