PHP Functions
A function gives an operation a name and a contract. Keep a calculation separate from page output so the same logic can be tested without parsing HTML.
How it works
Parameters receive inputs and a return statement supplies a value to the caller. Type declarations describe accepted values and the result, while validation enforces business constraints inside that type range. A positive integer is a stronger rule than int alone. Choose meaningful names and avoid a function that prints, mutates several globals and returns a loosely related value.
Run it locally
Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.
php -l functions.php
php functions.phpDownload this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.
Example
<?php
declare(strict_types=1);
function remaining(int $stock, int $borrowed): int {
if ($stock < 0 || $borrowed < 0 || $borrowed > $stock) {
throw new InvalidArgumentException("Invalid stock counts");
}
return $stock - $borrowed;
}
echo remaining(12, 5), "\n";
Expected result
7The function accepts valid counts and returns the difference without printing it. A caller can display seven or assert it in a test. Invalid ranges are rejected before subtraction, so a negative result cannot quietly represent available stock in this small model. Concurrency and persistence are outside this pure calculation’s responsibility.
Check the official PHP manual for detailed version and API contracts.