Thuta Learning
PHP
IntermediateProgrammingBeginner

Functions

PHPLesson 1430 min

What you'll walk away with

  • Write functions with parameter types, return types, nullable (?int) and union (int|float) types
  • Tell echo from return and make results reusable by the caller
  • Use default values, named arguments and variadic (...$items) parameters
  • Explain function scope and choose between a closure (use), an arrow function (fn) and a static variable
  • Explain what passing an argument by value and by reference (&) does

Explain it simply

Explain it simply

A function is a named piece of code: you write it once and call it from many places. Put logic that keeps coming back, such as price calculations, text formatting, input checks and database helpers, into functions and your code stays tidy and easy to change.

Picture a function as a small machine. You feed arguments in at one end, it works on its own, and it hands one return value back at the other end. A good function does one job, and because it returns its result instead of printing it, the caller decides what to do next.

Problem → Why → Solution

The problem: the result stays in echo, and the variable cannot be seen

Most people who write their first functions run into one of these two mistakes. The first is echoing a result instead of returning it: 1000 appears on screen, so it looks as if it works, but the variable holds null and every later calculation is wrong. The second is expecting a function to see a variable defined outside it, which PHP does not allow.

Running the code below prints 1000 and then Total with shipping: 500, not 1500. Then addTax() raises Warning: Undefined variable $taxRate and returns 100 with no tax applied.

broken-functions.php
<?php
function calculateTotal($price, $qty) {
    echo $price * $qty;            // prints, but returns nothing
}
$total = calculateTotal(250, 4);   // $total is null
$withShipping = $total + 500;      // 500, not 1500
echo "\nTotal with shipping: $withShipping\n";

$taxRate = 0.05;
function addTax($price) {
    return $price * (1 + $taxRate); // $taxRate does not exist in here
}
echo addTax(100), "\n";

Why does this happen?

echo only sends text to the output; it does not hand the value back to the caller, and a function without a return gives back null. On top of that, every PHP function has its own local scope and cannot see outside variables automatically, so $taxRate is treated as a variable with no value. The cure is to return the result and to pass in whatever the function needs as a parameter.

Core concept: a function is a contract with its own scope

You declare a function as function name(parameters): returnType { ... } and call it as name(arguments). The parameters become local variables inside the function, and a return statement sends one value back to the caller and ends the function at once. Every variable created inside disappears when the function ends, and outside variables are invisible from within. There are three ways to bring a value in: a parameter (best), the use clause of a closure, and the global keyword (avoid it).

Type declarations turn a function into a contract. int $qty says "give me an integer" and : float promises "I will return a float". ?string means string or null, a union type such as int|float means either listed type, and void means no useful value comes back. A wrong type makes PHP throw a TypeError. By default, though, PHP quietly converts values such as the numeric string "5" to int, which the strict_types lesson covers in detail.

FormExampleMeaning
Typedint $qtythe value passed in must be an int
Defaultstring $role = "member"used when the caller omits it
Nullable?int $limitan int or null may be passed
Variadicint ...$numberscollects the remaining arguments into an array
By referencearray &$listmodifies the caller's own variable

Arguments are passed by value, so changing a parameter inside the function does not touch the caller's variable (even an array is copied). Only an & before the parameter lets the function change the caller's variable directly. Since PHP 8 you can also pass arguments by name, as in createUser(active: false), which lets you skip one optional parameter and set a later one, and ...$items accepts any number of arguments.

Mental model: a contract in a private room
  1. Caller passes arguments in
  2. PHP checks and copies them to locals
  3. Body runs in its own private scope
  4. return hands one value back

If the function needs something from outside, pass it in as a parameter; if it must give something out, return it.

General pattern

php
function name(Type $required, Type $optional = default, Type ...$rest): ReturnType
{
    // local variables live only inside here
    return $value;
}

$closure = function (Type $x) use ($outer): ReturnType { return $value; };
$arrow = fn(Type $x): ReturnType => expression;

name(optional: value, required: value);   // named arguments

Required parameters come first, parameters with defaults follow, and a variadic parameter goes last. A closure asks for outer variables with use, while an arrow function captures them automatically by value. Named arguments can be written in any order.

Example: a discount function

This function takes an original price and a discount percentage and returns the final price. Because the function returns the result instead of printing it, the caller can echo it, store it in a variable or feed it into another calculation. The same function is called three ways below.

discount.php
<?php
function calculateDiscountPrice(float $price, int $discountPercent = 0): float
{
    $discountAmount = $price * ($discountPercent / 100);
    return $price - $discountAmount;
}

echo "Final price: " . calculateDiscountPrice(20000, 15) . " MMK\n";
echo "No discount: " . calculateDiscountPrice(20000) . " MMK\n";
echo "Named: " . calculateDiscountPrice(discountPercent: 50, price: 8000) . " MMK\n";

Code breakdown

  1. Signaturefunction calculateDiscountPrice(float $price, int $discountPercent = 0): float

    Both parameters are typed, and $discountPercent has a default of 0, which makes it optional. : float is the promise that a float comes back.

  2. Local variable$discountAmount = $price * ($discountPercent / 100);

    $discountAmount is a local variable that exists only inside the function; once the function ends it is gone and cannot be reached by that name from outside.

  3. returnreturn $price - $discountAmount;

    return sends the value to the caller and ends the function. 20000 - 3000 gives 17000.

  4. Default usedcalculateDiscountPrice(20000)

    With only one argument, $discountPercent falls back to its default of 0, so the price stays at 20000.

  5. Named argumentscalculateDiscountPrice(discountPercent: 50, price: 8000)

    Passing by name lets you change the order, and it makes the call readable on the spot because each value is labelled.

You should see
Final price: 17000 MMK
No discount: 20000 MMK
Named: 4000 MMK

Type declarations: nullable, union and void

Sometimes a function has to say "I found nothing". A nullable return type such as ?string is ideal for that, because the signature itself warns the caller that null is possible. A union type such as int|float (available since PHP 8.0) accepts two types. A void function exists only for its side effect, and if you capture its result you get null.

types.php
<?php
function findUsername(int $id): ?string
{
    $users = [1 => "Aye", 2 => "Min"];
    return $users[$id] ?? null;
}

function half(int|float $n): float
{
    return $n / 2;
}

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

var_dump(findUsername(1));
var_dump(findUsername(9));
var_dump(half(5));
var_dump(half(2.5));
logLine("saved");
$result = logLine("again");
var_dump($result);

This prints string(3) "Aye", NULL, float(2.5) and float(1.25), then [log] saved, [log] again and finally NULL. When you call a function that returns ?string, remember to handle null with ?? or a === null check.

Defaults, named arguments and variadics

Put parameters with defaults after the required ones. An optional parameter placed before a required one produces a PHP 8 deprecation notice and is treated as required. Named arguments help when you want to skip one default and set a later one. A variadic parameter ...$numbers receives its arguments as an array, and at the call site ...$array spreads an array back into separate arguments.

arguments.php
<?php
function createUser(string $name, string $role = "member", bool $active = true): string
{
    return $name . " (" . $role . ", " . ($active ? "active" : "inactive") . ")";
}

echo createUser("Aye"), "\n";
echo createUser("Min", "admin"), "\n";
echo createUser("Hla", active: false), "\n";
echo createUser(active: false, name: "Su"), "\n";

function sum(int|float ...$numbers): int|float
{
    return array_sum($numbers);
}

$more = [4, 5, 6];
echo sum(), " ", sum(1, 2, 3), " ", sum(...$more), "\n";

The output is Aye (member, active), Min (admin, active), Hla (member, inactive), Su (member, inactive), and then 0 6 15. A named argument uses the parameter's own name, so renaming a parameter later can break callers that use that name.

Closures, arrow functions, static variables and references

A closure is an anonymous function you can store in a variable. With use ($taxRate) it copies the outer variable's value at the moment the closure is created, so later changes to the outer variable do not affect it. With use (&$count) the & shares the very same variable instead. An arrow function, fn, is a short form for a single expression and captures outer variables by value without needing use. A static variable remembers its value between calls.

closures.php
<?php
$taxRate = 0.05;
$withTax = function (float $price) use ($taxRate): float {
    return round($price * (1 + $taxRate), 2);
};

$discount = 10;
$afterDiscount = fn(float $price): float => $price * (1 - $discount / 100);

$taxRate = 0.5;   // changed after the closures were created
$discount = 90;
echo $withTax(100), " ", $afterDiscount(100), "\n";

$count = 0;
$increment = function () use (&$count): void {
    $count++;
};
$increment();
$increment();
echo "count = $count\n";

function nextId(): int
{
    static $id = 0;
    return ++$id;
}
echo nextId(), nextId(), nextId(), "\n";

function addTag(array &$tags, string $tag): void
{
    $tags[] = $tag;
}
$tags = ["php"];
addTag($tags, "forms");
echo implode(",", $tags), "\n";

echo implode(",", array_map(fn(int $n): int => $n * $n, [1, 2, 3])), "\n";

The output is 105 90, count = 2, 123, php,forms and 1,4,9. Notice that 105 and 90 do not change even though $taxRate and $discount were altered afterwards, because the values were copied at creation. Calling a by-reference parameter (array &$tags) with a literal array raises Error: ... could not be passed by reference, so a parameter with & must receive a variable.

In real projects

Where this shows up in real projects

In real projects a function signature becomes documentation for the team. Reading formatMoney(int $cents, string $currency = "USD"): string tells you how to call it without opening the body. Many of PHP's built-in functions take callbacks, so pairing closures with array_map(), array_filter() and usort() is everyday code, and strlen(...) turns even a built-in function into a callable value.

helper.php
<?php
function e(string $text): string
{
    return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

echo "<p>" . e("Tom & \"Jerry\"") . "</p>\n";

$products = [["name" => "Pen", "price" => 5], ["name" => "Clip", "price" => 2]];
usort($products, fn(array $a, array $b): int => $a["price"] <=> $b["price"]);
echo $products[0]["name"], "\n";

This tiny helper shows the mark of a good function: it does one job and returns its result. That lets you escape right where the value goes into HTML, and makes the function easy to unit test. The more a function echoes, writes to a database or changes globals (side effects), the harder it is to reuse and test, so keep the calculating part separate from the printing part.

Common mistakes

Common mistakes

1. Using echo instead of return

Calling function total() { echo $a * $b; } as $x = total(); leaves $x as null. The number appears on screen, so it seems to work, but you cannot use the result in later calculations. Write return $a * $b; and do the printing at the call site.

2. Expecting to see an outer variable inside the function

Defining $taxRate outside a function and using it inside gives Warning: Undefined variable $taxRate, and the value is treated as null. Fix it by passing it as a parameter, by using use ($taxRate) on a closure, or by writing an arrow function with fn. Avoid global $taxRate, which hides what the function depends on.

3. Assuming a changed argument is visible to the caller

function bump(array $list) { $list[] = 99; } does not change the caller's array, because the array is passed by value and only a copy is edited. Return the modified array instead, and use a reference such as array &$list only when you truly must change the caller's own variable.

4. Putting an optional parameter before a required one

Writing function f(int $a = 1, int $b) makes PHP 8 print Deprecated: Optional parameter $a declared before required parameter $b is implicitly treated as a required parameter. The default becomes useless. Always place parameters with defaults last.

Best practices

Best practices

  • Give each function one job and name it with a verb (formatPrice, isValidEmail).
  • Type every parameter and return value, and use ?type when a result may be absent so the signature shows it.
  • Prefer return over echo and escape only at the point where HTML is produced.
  • When a call has three or four boolean flags in a row, use named arguments or group them in one array.

Mini challenge

Mini challenge: bill-splitting helpers

Write three functions for splitting a restaurant bill among friends and combine them. Type everything, return results, and do not echo inside the functions.

  • splitBill(float $total, int $people = 2, float $tipPercent = 10.0): float adds the tip and returns one person's share rounded to 2 decimals
  • maxOrNull(int ...$numbers): ?int returns the largest value, or null when no arguments are given
  • makeMultiplier(int $factor): Closure returns a closure that captures $factor with use
  • Call splitBill once with named arguments and use makeMultiplier with array_map()
bill.php
<?php
function splitBill(/* TODO: total, people = 2, tipPercent = 10.0 */): float
{
    // TODO: add the tip, divide by the people, round to 2 decimals
}

function maxOrNull(/* TODO: variadic int parameter */): ?int
{
    // TODO: null when no numbers were passed
}

function makeMultiplier(int $factor): Closure
{
    // TODO: return a function(int $n) that captures $factor with use
}

// TODO: print a default split, a named-argument split, both max cases
// TODO: print array_map(makeMultiplier(3), [1, 2, 3]) joined with ", "

Expected: Expected output: Default split: 49.50 Four people, no tip: 30.00 Max: 9, empty: none Tripled: 3, 6, 9

Show hint

A variadic parameter is an array, so test $numbers === [] and otherwise use max($numbers). number_format($value, 2) prints exactly two decimals. Call splitBill with named arguments in a different order, for example splitBill(total: 120, tipPercent: 0, people: 4).

Show solution
bill.php
<?php
function splitBill(float $total, int $people = 2, float $tipPercent = 10.0): float
{
    return round($total * (1 + $tipPercent / 100) / $people, 2);
}

function maxOrNull(int ...$numbers): ?int
{
    return $numbers === [] ? null : max($numbers);
}

function makeMultiplier(int $factor): Closure
{
    return function (int $n) use ($factor): int {
        return $n * $factor;
    };
}

echo "Default split: " . number_format(splitBill(90.0), 2) . "\n";
echo "Four people, no tip: "
    . number_format(splitBill(total: 120, tipPercent: 0, people: 4), 2) . "\n";
echo "Max: " . (maxOrNull(3, 9, 4) ?? "none")
    . ", empty: " . (maxOrNull() ?? "none") . "\n";
echo "Tripled: " . implode(", ", array_map(makeMultiplier(3), [1, 2, 3])) . "\n";

Quick quiz 1 / 3

Given function box(int $w, int $h = 1, int $d = 1): int { return $w * $h * $d; }, what does echo box(5, d: 3); print?

Quick quiz 2 / 3

What does $rate = 0.1; $f = fn($p) => $p * $rate; $rate = 0.5; echo $f(100); print?

Quick quiz 3 / 3

After calling counter(); counter(); echo counter(); on function counter() { static $n = 0; return ++$n; }, what is printed?

What to remember

  • A function has its own local scope: pass outside values in as parameters (or via use on a closure) and give results back with return, not echo.
  • Parameter and return types, ?int, int|float and void make a function a contract, and defaults, named and variadic arguments make calls flexible.
  • A closure copies values with use, an arrow function fn captures by value automatically, and a static variable remembers its value between calls.
  • Arguments are passed by value; reach for & (by reference) only when you must change the caller's own variable.

PHP Language Reference — PHP Documentation Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Functions | Thuta Learning