PHP / CHAPTER 03
Functions and typed boundaries
BeginnerSeparate output, return values, and mutation.
By the end of this chapter
- Use parameter and return declarations
- Recognize strict_types at the calling file
- Avoid unintended reference parameters
The idea
A function packages a transformation behind parameters and a return value. Echo writes output; return provides data to the caller and ends the invocation. Parameter and return declarations describe accepted values, but scalar coercion behavior also depends on strict_types. A strict declaration belongs at the top of a PHP file and affects calls made from that file rather than changing every caller in the application.
Ordinary parameters do not give a function permission to rebind the caller’s variable. An ampersand parameter explicitly requests reference behavior and should be used only when changing that variable is part of the contract. Objects have their own identity considerations, so distinguish replacing a variable from changing an object’s properties. Prefer returning a new result for transformations that callers need to reason about independently.
<?php
declare(strict_types=1);
function subtotal(int $quantity, int $price): int {
return $quantity * $price;
}
echo subtotal(3, 7), "
";21
The strict calling file supplies two integers, and the function returns their product. Echo displays the returned result outside the calculation.
Try it yourself
Write a typed function returning an uppercase label without printing or modifying its argument.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING