Functions — PHP

A function is code with a name, so it can be called many times. function name($param) { return ...; } creates a function, and name(argument) calls it…

This function looks fine: function calculate(int $a, int $b): int { $a + $b; }. The sum is calculated, but echo calculate(2, 3); never prints 5. Only one word is missing, and that word is one of the most important parts of this lesson.

A function is a group of code lines with a name, so it can be called (run) many times with different inputs. Picture a recipe card in the kitchen of Mrs. Tini's Stall: "Calculate the total: price times the number of portions." The recipe is written once. For every order, Mrs. Tini uses the same recipe with that order's numbers, then hands the result to the cashier. In code, the recipe card is the function, the order's numbers are the inputs sent to it, and the result for the cashier is the value that comes out of the function. In the Type System lesson you saw the function totalPrice briefly. Here you see how it works.

Writing and calling a function

<?php
function totalPrice(int $price, int $quantity): int {
    return $price * $quantity;
}

echo totalPrice(15, 2) . "\n"; // 30
echo totalPrice(5, 3);         // 15

This is what happens when totalPrice(15, 2) is called:

Step What happens
1 $price gets 15, $quantity gets 2, in order of position
2 return $price * $quantity calculates 30 and sends it out
3 echo prints 30 where the function was called

One recipe, many orders: the second call fills $price with 5 and $quantity with 3, so the result is 15.

return: the result sent back out

<?php
function calculate(int $a, int $b): int {
    $a + $b;
}

echo calculate(2, 3);
Fatal error: Uncaught TypeError: calculate(): Return value must be of type int, none returned in /app/till.php:4

$a + $b; is calculated, but the result is thrown away because it isn't returned. Without : int, PHP doesn't refuse, but the echo prints nothing. The fix is one word: write return $a + $b;.

An echo inside a function is no replacement for return either. For example, say the function printTotal holds only an echo. It does print the total, but $total = printTotal(15, 2); leaves $total holding null. So the total can't be used again. Make it a habit: the function returns its result, and the echo is written outside the function.

Default parameters and named arguments

In this version, the parameter $quantity has a default value:

<?php
function totalPrice(int $price, int $quantity = 1): int {
    return $price * $quantity;
}

echo totalPrice(15) . "\n";           // 15
echo totalPrice(15, 2) . "\n";        // 30
echo totalPrice(quantity: 3, price: 5); // 15
Fatal error: Uncaught ArgumentCountError: Too few arguments to function totalPrice(), 0 passed in /app/till.php on line 6 and at least 1 expected in /app/till.php:2

A default value can be text too: function greet($name = "World") { return "Hello $name"; } makes greet() return Hello World.

Variables inside and outside a function

In this code, $discount is created outside the function:

<?php
$discount = 2;

function finalPrice($price) {
    return $price - $discount;
}

echo finalPrice(15);
Warning: Undefined variable $discount in /app/till.php on line 5
15

A function only sees its parameters and the variables created inside that function. This rule is called scope (the area where a variable can be seen). $discount was created outside, so it can't be seen inside the function. PHP treats it as null, and null counts as 0 in a calculation, so 0 is subtracted. Send the value in as a parameter: function finalPrice($price, $discount).

A parameter also holds a copy of its argument's value. The exception is a parameter written with &, like array &$stock (pass by reference): the function receives the original variable, not a copy, and can change it directly. The parameter of sort uses & too, so sort($prices) in the Advanced Arrays lesson later changes $prices directly.

Arrow functions and closures

A function can also be made without a name and stored in a variable. This form is often handed to another function, such as array_map in the Advanced Arrays lesson. In this code, two functions without names add the shipping cost to a total:

<?php
$shipping = 5;

$plusShipping = fn($total) => $total + $shipping;
$withShipping = function ($total) use ($shipping) {
    return $total + $shipping;
};

echo $plusShipping(30) . "\n"; // 35
echo $withShipping(30);         // 35

📌 Variadics: any number of arguments

function sumAll(int ...$prices): int {
    return array_sum($prices);
}

echo sumAll(15, 5, 2); // 22

...$prices gathers every argument sent into one array, however many there are. Then array_sum($prices) adds up all the items of that array.

⚠️ Results that get lost on the way

TL;DR: A function is code with a name, so it can be called many times. function name($param) { return ...; } creates a function, and name(argument) calls it. Arguments (the values sent) fill the parameters (the function's own variables) by position, or by name (quantity: 3). return sends the result to the place where the function was called. Without return the result is null, and when the result type is written as : int, PHP stops with a TypeError. $quantity = 1 is the default value for an argument that isn't sent. A function only sees its own parameters, not the variables outside it. A function without a name comes in two forms: fn($x) => expression returns automatically and can read outside variables, while function ($x) use ($y) { return ...; } needs use and return.

⚡ One recipe, many orders

Write:

<?php
function totalPrice(int $price, int $quantity): int {
    return $price * $quantity;
}

echo totalPrice(15, 2) . "\n"; // 30
echo totalPrice(5, 3);         // 15

Meaning: function creates a function named totalPrice: code written once, then called many times. $price and $quantity are parameters (variables filled when the function is called). 15 and 2 are the arguments (the values sent), and they fill the parameters by position. return sends the result back to where the function was called, and then echo prints it.

⚡ The word that's easy to forget

Guess first: function calculate(int $a, int $b): int { $a + $b; }, what does echo calculate(2, 3); write?

Not 5: PHP stops with Return value must be of type int, none returned. This function has no return, so the result of $a + $b is calculated and thrown away, even though the result type must be : int. The fix is one word: return $a + $b;.

Meaning: An echo inside a function is no replacement for return: the function's result is still null. Write the echo outside the function.

⚡ Defaults and named arguments

Write:

echo totalPrice(15) . "\n";              // 15
echo totalPrice(quantity: 3, price: 5); // 15

Meaning: Here totalPrice is written with int $quantity = 1. When $quantity isn't sent, it uses that default value, 1. Named arguments are sent together with their parameter's name, like quantity: 3, so they can come in any order.

⚡ A function only sees its parameters

Guess first: $discount = 2; is written outside the function finalPrice($price), which calculates $price - $discount. Can $discount be used inside that function?

No. PHP gives Warning: Undefined variable $discount (an unknown variable). $discount is treated as null, which counts as 0 in a calculation, so the price does not go down.

Meaning: A function only sees its parameters and the variables created inside it. Send an outside value in as a parameter: function finalPrice($price, $discount).

What you will learn