Declaring a function
function returns a value; echo inside it is already a side effect.
A function is declared with function name(...). A name exists once in a program. Declaring it again is a fatal error. The result comes back with return. Code after return in that branch does not run.
echo inside a function prints immediately. For a library function that is almost always a mistake: the caller did not ask for text in the response, it asked for a value. The boundary prints; the function returns. That is exactly how func-mode tasks work: return, no echo.
The return type goes after the parentheses: function sum(int $a, int $b): int. Without declare(strict_types=1) PHP still converts numbers in weak mode. With that directive at the top of the file it converts less and more honestly. In func mode you can skip the directive unless you promise types yourself.
A small function does one thing. If the name sounds like parseAndSaveAndMail, there are three functions inside. A name without a verb (user) is usually bad: it is unclear whether the function creates, finds or checks.
Practice
What to give the caller
The function will be called from another function. How do you hand back the result?
- echo
- return
- var_dump
- print_r
After return
Will an echo placed right after return in the same branch run? Answer yes or no.
Clamp
Write function clamp($n, $lo, $hi). Return $n, but not less than $lo and not greater than $hi.