Functions in PHP
A function is a named block of code that performs a task and can be invoked repeatedly from anywhere in a script. PHP functions are declared with the function keyword, are not case-sensitive by name (though this style is discouraged), and can accept zero or more parameters. Since PHP 7, parameters and return values can carry type declarations, which the engine checks at call time and can enforce strictly when declare(strict_types=1) is set at the top of a file. Functions are first-class in the sense that they can be stored in variables, passed as callbacks, and returned from other functions, which underpins much of PHP's support for functional-style programming.
Cricket analogy: A function like calculateStrikeRate() is a named routine a scorer can call repeatedly for any batter, taking runs and balls as parameters; since PHP 7, declaring int $runs and float $strikeRate types (enforced strictly under declare(strict_types=1)) is like the ICC scoring rules rejecting a fractional ball count outright.
Declaring and Typing Functions
A basic declaration names the function, lists its parameters, and optionally declares a return type after a colon. Parameters can have default values, which must come after any parameters without defaults (unless using named arguments). Type declarations may be scalar types (int, float, string, bool), compound types (array, iterable, object), class/interface names, self, static, or nullable types written with a leading question mark such as ?int. Union types, introduced in PHP 8.0, let a parameter or return value accept more than one type, for example int|string.
Cricket analogy: A function like function rateBowler(string $name, int $wickets, ?float $economy = null): string names its parameters and declares a return type; giving $economy a default value after the required parameters mirrors how a scorecard lists mandatory fields (name, wickets) before optional ones (economy rate).
declare(strict_types=1);
function formatPrice(float $amount, string $currency = 'USD'): string
{
return sprintf('%s %.2f', $currency, $amount);
}
echo formatPrice(19.5); // USD 19.50
echo formatPrice(19.5, 'EUR'); // EUR 19.50
// Union return type (PHP 8.0+)
function findUser(int $id): array|null
{
$users = [1 => ['id' => 1, 'name' => 'Ada']];
return $users[$id] ?? null;
}Variadic Parameters and Argument Unpacking
A function can accept an arbitrary number of arguments using the ... (splat) operator before the last parameter, which collects the remaining arguments into an array. The same operator can be used at the call site to unpack an array or generator into individual arguments. Variadics can be typed, meaning every collected argument must match the declared type, and PHP 8.1 allows named arguments to be unpacked as well when the array keys are strings.
Cricket analogy: A function like function totalRuns(string $match, int ...$innings) uses the splat operator to collect an arbitrary number of innings scores into one array, like a scorer summing however many innings a Test match happens to have, five-day or rain-shortened.
function sum(int ...$numbers): int
{
return array_sum($numbers);
}
echo sum(1, 2, 3); // 6
$values = [4, 5, 6];
echo sum(...$values); // 15 (argument unpacking)Pass by Value vs. Pass by Reference
By default, arguments are passed by value, so modifying a parameter inside a function does not affect the caller's variable. Prefixing a parameter with an ampersand (&) makes it a reference parameter, so changes inside the function are visible to the caller. References are useful for functions that mutate large arrays in place (avoiding a copy) but should be used sparingly because they make code harder to reason about and can produce surprising side effects, especially inside loops with foreach (... as &$item).
Cricket analogy: Passing a batter's score by value into a function that adjusts it for a not-out bonus doesn't change the official scoresheet; but passing the scoresheet array by reference with &$scoresheet lets the function edit it directly, useful for a bulk end-of-innings update but risky if used carelessly across overs.
function doubleInPlace(array &$numbers): void
{
foreach ($numbers as &$n) {
$n *= 2;
}
unset($n); // break the reference to avoid bugs later
}
$nums = [1, 2, 3];
doubleInPlace($nums);
print_r($nums); // [2, 4, 6]Think of a function signature as a contract: the parameter types promise what the function accepts, and the return type promises what it hands back. With strict_types=1, PHP enforces that contract exactly rather than silently coercing types, catching bugs far earlier than PHP's traditional loose-typing behavior.
Forgetting to unset() a reference variable created in a foreach (... as &$value) loop is a classic PHP bug: the reference lingers and can silently overwrite the last array element if the same variable name is reused in a later loop.
- Functions are declared with
function, can have typed parameters and return types, and default parameter values must follow required ones. declare(strict_types=1)makes PHP enforce parameter and return types exactly instead of coercing them.- Union types (PHP 8.0+) allow a parameter or return value to accept more than one declared type.
- The
...splat operator both collects variadic arguments into an array and unpacks arrays into arguments at a call site. - Arguments pass by value by default; prefixing a parameter with
&makes it pass by reference, which mutates the caller's variable. - Always
unset()a reference variable from aforeach (&$x)loop to avoid it leaking into subsequent code.
Practice what you learned
1. What happens when a function parameter with a default value is placed before a required parameter without one?
2. What does the `...` operator do when used in a function call like `sum(...$values)`?
3. Which statement about passing arguments by reference in PHP is correct?
4. What is the effect of `declare(strict_types=1);` at the top of a PHP file?
5. Which return type indicates a function does not return any meaningful value?
Was this page helpful?
You May Also Like
Indexed and Associative Arrays
Understand PHP's single array type used for both ordered lists and key-value maps, including creation, iteration, and common manipulation patterns.
Array Functions
Survey PHP's extensive standard-library array functions for transforming, filtering, searching, and reducing arrays without manual loops.
Type Declarations and Strict Types
PHP supports optional scalar and object type declarations on parameters, return values, and properties, with strict_types controlling how aggressively the engine coerces mismatched values.
Named Arguments and the Nullsafe Operator
Named arguments let callers pass function parameters by name in any order, and the nullsafe operator short-circuits chained property/method access safely when any link is null.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics