PHP — Typed functions and return values
A PHP function can declare argument and return types. Returning an integer lets the caller calculate with the value independently of how it is displayed.
A simple example
Call a function with 2
- Start with Argument 2
- Do this Double the argument
- Result 4
<?php
function twice(int $n): int {
return $n + $n;
}
echo twice(2), PHP_EOL;
4
Calculate how many boxes an order needs
The scalar declarations make the input and result types explicit. With strict_types enabled, incompatible arguments from this file trigger a TypeError. Keep output in the caller.
A library ships 17 books in cartons that hold eight. Two cartons take sixteen books, leaving one book that still needs a carton. An order of exactly sixteen needs only two.
Run the example
PHP 8 or later. Run these commands from the directory containing the example.
php lesson.php
<?php
declare(strict_types=1);
function boxesNeeded(int $items, int $capacity): int
{
return intdiv($items, $capacity) + ($items % $capacity === 0 ? 0 : 1);
}
echo boxesNeeded(17, 8), PHP_EOL;
echo boxesNeeded(16, 8), PHP_EOL;
3 2
The input contract is a nonnegative whole-number item count and a positive box capacity. Seventeen items fill two boxes of eight with one item left over. Sixteen items fill exactly two boxes.
Try it yourself
How many boxes do zero items need?
Check your answer
Zero. The quotient and remainder are both zero. A zero capacity is outside the function’s contract because division by zero is undefined.