Skip to the workspace
Pebellslearn by building
Functions  ›  Lesson

Declaring Functions: Parameters and Return Values

Function Declaration 13 minA function declaration defines reusable instructions with parameters and a returned result. PHP permits parameter and return type declarations, but does not require them everywhere.

php / Declaring Functions: Parameters and Return Values

Explore each scene at your own pace.

01 · The rule

The rule

Declaring Functions: Parameters and Return Values

A function declaration defines reusable instructions with parameters and a returned result. PHP permits parameter and return type declarations, but does not require them everywhere.

Follow arguments into parameters and the returned result back to the caller.

Pageturn works out a line total, a price times a quantity, in the basket, at checkout and on the invoice. Copy that formula into three places and one day only two of them get fixed. A function puts the formula in one place, under a name, with clear inputs and a clear output.

The rule

Parameters go in, one value comes out with return.

<?php
function lineTotal(float $price, int $qty): float
{
    return $price * $qty;
}

echo lineTotal(9.99, 2);   // 19.98
$total = lineTotal(7.50, 3) + lineTotal(12.00, 1);   // 34.5

Reading the declaration left to right:

  • function lineTotal names it. Function names are case-insensitive, but match the declared spelling anyway.
  • (float $price, int $qty) are the parameters: local variables that receive the arguments you pass when calling. The types are optional but strongly recommended.
  • : float is the return type: what the function promises to give back.
  • return ends the function immediately and hands back a value. Code after it does not run.

A function with no return gives back null. If it deliberately returns nothing, declare it : void.

What types do. With int $qty, calling lineTotal(9.99, "two") throws a TypeError: the mistake is caught at the door. By default PHP still converts compatible values, so "2" becomes 2. Put declare(strict_types=1); as the first statement of a file to switch that off, so the call must pass a real int.

Functions can be called before they appear in the file, as long as they are declared at the top level: PHP reads the whole file first.

Arguments are copied in by default, so changing $qty inside the function does not change the caller's variable.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.