Step 1 of 5 · Reading · ~3 min
Learn
Functions
Functions
A function is a named block you can call from anywhere: inputs go in, one value comes out. In PHP it is also the boundary where types actually get checked.
Defining and calling
<?php
function shippingCost(float $kg, string $tier = "standard"): float {
$base = $tier === "express" ? 9.0 : 4.0;
return $base + $kg * 1.5;
}
printf("%.2f\n", shippingCost(2.0));
printf("%.2f\n", shippingCost(2.0, "express"));
printf("%.2f\n", shippingCost(0.5));
//> 7.00
//> 12.00
//> 4.75
Reading the signature left to right: float $kg is a required typed parameter, string $tier = "standard" is an optional one carrying a default, and : float is the return type. Parameters with defaults must come after all the required ones — the other order is a mistake PHP will complain about.
What do the type declarations buy me?
By default PHP is coercive: it converts an argument when it can, and throws only when it cannot.
<?php
function square(int $n): int { return $n * $n; }
var_dump(square("7"));
//> int(49)
Add one line at the very top of the file and the same call becomes an error instead:
<?php
declare(strict_types=1);
Without strict_types | With declare(strict_types=1); |
|---|---|
square("7") gives 49 | square("7") throws a TypeError |
square("abc") throws a TypeError | square("abc") throws a TypeError |
| Convenient, and silently lossy | Loud, and bugs surface where they start |
New code should use it. Several starters later in this course already have that line in place.
A declared return type is a promise
If a function says : int, it has to actually return an int on every path. Falling off the end returns nothing, and PHP raises a TypeError complaining that the return value must be of type int and none was returned. That is exactly what an unfinished function body does — which makes it a useful signal rather than a mystery.
Functions cannot see your other variables
This surprises people arriving from Python or JavaScript. A function body gets a fresh, empty scope; the outer $taxRate simply does not exist inside it.
<?php
$taxRate = 0.2;
// ✗ broken — $taxRate is undefined in here, so the maths has nothing to work with
function withTaxBroken(float $amount): float {
return $amount * $taxRate;
}
// ✓ pass in what you need
function withTax(float $amount, float $rate): float {
return $amount * (1 + $rate);
}
printf("%.2f\n", withTax(50.0, $taxRate));
//> 60.00
PHP does offer global $taxRate; to reach outward, but parameters are clearer, testable, and impossible to break from a distance. Treat global as a smell.
Remembering between calls
A static variable inside a function is initialised once and survives every later call:
<?php
function ticket(): int {
static $next = 1;
return $next++;
}
echo ticket(), ticket(), ticket(), "\n";
//> 123
Accepting any number of arguments
<?php
function total(int ...$amounts): int {
return array_sum($amounts);
}
echo total(3, 8, 2), "\n";
echo total(...[1, 2, 3, 4]), "\n";
//> 13
//> 10
In a declaration, ... collects the remaining arguments into an array. At a call site, ... spreads an array back out into separate arguments. Same three dots, opposite directions.
One legacy quirk
Function names are case-insensitive: shippingCost(...) and SHIPPINGCOST(...) reach the same function. Variable names are not — $total and $Total are two entirely different variables. Pick one convention (camelCase for functions is the PSR standard) and stay with it.
Your exercise
Square It asks you to fill in function square(int $n): int so it returns $n * $n. The starter already reads the input and prints the result.
The mistake the grader catches is echoing instead of returning. Write echo $n * $n; inside the function and the value prints once from inside, the function then returns nothing, and PHP throws a TypeError about the declared int return — so the test sees garbled output and a crash. The whole body is one return statement. The hidden case feeds -5 and expects 25, so resist adding an abs() or a sign check; squaring already handles it.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…