Functions are how you name and reuse logic, and PHP's argument features make call sites readable.
Declare a function with function name(params): returnType { ... }. Type declarations are optional but strongly recommended:
function greet(string $name, string $greeting = 'Hello'): string {
return "$greeting, $name!";
}Argument features worth knowing:
- Default values make parameters optional. Parameters with defaults should come last.
- Named arguments (PHP 8.0) pass by name and skip defaults:
greet(greeting: 'Hi', name: 'Bo'). Great for functions with many optional flags, such ashtmlspecialchars($s, double_encode: false). - Variadics collect extra arguments into an array:
function sum(int ...$nums). The spread operator does the reverse at the call site:sum(...$list). - A
?stringtype means string or null;voidmeans the function returns nothing.
Arguments are passed by value. Prefix a parameter with & to pass by reference (function addOne(array &$a)), but use this sparingly; returning a new value is clearer.
Variables inside a function are local. Code outside can't see them and the function can't see outer variables unless they are passed in (avoid the global keyword). Use static $count = 0; inside a function for a value that persists across calls.
Functions can be called before their definition in the same file, because PHP hoists top-level function declarations.
Example
<?php
function greet(string $name, string $greeting = 'Hello'): string {
return "$greeting, $name!";
}
function sum(int ...$nums): int {
return array_sum($nums);
}
function counter(): int {
static $n = 0;
return ++$n;
}
echo greet('Ada'), "\n"; // Hello, Ada!
echo greet(greeting: 'Hi', name: 'Bo'), "\n"; // Hi, Bo!
echo sum(1, 2, 3), "\n"; // 6
$list = [4, 5];
echo sum(...$list), "\n"; // 9
counter(); counter();
echo counter(), "\n"; // 3Remember
- Type your parameters and return values
- Named arguments skip defaults and document intent
- ...$args collects extras; ...$list spreads an array into arguments
Watch out for
- Expecting a function to see variables from the surrounding script; functions have their own scope.