Declaring Functions: Parameters and Return Values
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.5Reading the declaration left to right:
function lineTotalnames 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.: floatis the return type: what the function promises to give back.returnends 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.
The shortcut
Design a function by writing its signature first, as a sentence: "given these inputs, it returns this." If you cannot finish the sentence with one output, the function is doing two jobs.
The sentence
"Given a stock count and a requested quantity, it returns whether the order can be filled."
Drills
Answer fast — trust the rule.
What does a function return if it never reaches a return statement?
In lineTotal(9.99, 2), what are 9.99 and 2?
What happens to code written after a return inside the same block?
With strict_types off, what does lineTotal(9.99, "2") do?
Remember
- Parameters go in, one value comes out with
return. - Shortcut: write the signature as a sentence — inputs, then one output.
- Trap: no return means
null, and without strict_types PHP converts compatible arguments quietly.
