The Analogy: The Paint-Tinting Counter
At the back of a hardware shop stands a paint-tinting counter with a row of colorant canisters -- white, black, red, yellow, and more -- feeding a machine that squirts precise measures of each into a base tin and shakes it. A colour is a formula: so many shots of this, so many of that. The counter is where a recipe becomes a physical tin of paint, and the way the assistant conveys that recipe to the machine is exactly the problem of passing arguments to a function. The machine has a fixed set of inputs; the recipe has to be delivered into them correctly, or the colour comes out wrong.
The oldest way to deliver a formula is a bare list of numbers in a fixed, memorised order: "12, 4, 0, 30", meaning twelve of the first canister, four of the second, none of the third, thirty of the fourth. This is positional argument passing, and it works only as long as everyone remembers that the third slot is red and the fourth is white. Its weakness is glaring: transpose two numbers -- write "30, 4, 0, 12" by mistake -- and the machine cheerfully mixes a completely different colour, because every value is a perfectly valid number in a valid slot. Nothing is out of range, so nothing complains. The mistake is invisible until the lid comes off.
The better counters use a printed formula card that labels every amount: "white: 30, black: 12, yellow: 4". Now the order on the card does not matter, because each number is tied to its canister by name, and any canister you do not mention simply gets none. This is named arguments, and it removes the transposition hazard entirely while letting you skip the ones you want to leave at their default. Some formulas also say "and then add tint shots to taste" -- an open-ended run of extra measures the machine collects however many you give it -- which is a variadic parameter gathering the rest into one tray. And if you already hold a written card, you can feed the whole card into the machine at once and let it read each labelled amount into the right slot, which is argument unpacking: spreading an array into the call.
The failures follow the method. With positional delivery, the dangerous failure is the silent one: a transposed pair produces a valid but wrong colour, and no barrier catches it because the types and counts are all fine. With named delivery, the failures are loud and early -- name a canister the machine does not have and it stops at once rather than mixing something wrong. That trade is the whole lesson: positional passing is terse but couples the caller to an order they must never muddle, while named passing is more verbose but makes the call self-describing and turns a silent colour error into an immediate, obvious refusal.
Syntax or Core Structure
Arguments may be passed by position, in the order the parameters are declared, or by name, using the name: value syntax introduced in PHP 8.0. Named arguments may be given in any order and let you skip any parameter that has a default, supplying only the ones you want to change. A parameter with a default is optional; the default is used whenever the argument is not supplied by either means.
<?php
function label(string $text, int $width = 10, string $pad = '.'): string
{
return str_pad($text, $width, $pad);
}
echo label('OK'), "\n"; // both defaults: width 10, pad '.'
echo label('OK', 6), "\n"; // positional width 6
echo label('OK', pad: '-'), "\n"; // named: pad only, width stays 10
The first call supplies only the required text and takes both defaults. The second passes width positionally. The third uses a named argument to set pad while leaving width at its default of 10 -- something positional passing cannot do, since you would have to repeat the default 10 just to reach pad.
Output:
OK........
OK....
OK--------
The third line is ten characters wide because width kept its default; only the pad character changed. Named arguments shine precisely here, where a function has several optional parameters and a caller wants to set just one of the later ones.
Technical Depth: Four Ways to Pass, and the Spread Operator
The passing styles compared
There are four ways an argument can reach a parameter, and each has a place. The table sets out what each looks like and when it earns its keep.
| Style | At the call site | Best when |
|---|---|---|
| Positional | f(30, 12, 4) | Few parameters, an obvious order |
| Named | f(white: 30, yellow: 4) | Many optionals, or skipping middle defaults |
| Variadic collect | function f(int ...$n) | The count is open-ended |
| Spread unpack | f(...$array) | You already hold the values in an array |
Positional and named passing may be mixed in a single call, but every positional argument must come before the first named one; writing a positional argument after a named argument is a parse error. The rule exists because PHP fills positional slots first and then applies the named ones on top, so a trailing positional value would have no unambiguous slot to land in.
Collecting with variadics, spreading with the operator
The same ... token does two complementary jobs. In a parameter list, ...$nums collects any number of trailing arguments into an array. At a call site, ...$array spreads an array back out into separate arguments. Together they let a function accept a variable number of values and let a caller supply them from an array it already holds.
<?php
function total(int ...$nums): int
{
return array_sum($nums);
}
echo total(1, 2, 3), "\n"; // three separate arguments collected
$vals = [4, 5, 6, 7];
echo total(...$vals), "\n"; // an array spread into four arguments
In the first call, three integers are collected into $nums as [1, 2, 3] and summed. In the second, the four-element $vals array is spread by ... into four separate arguments, collected again into $nums as [4, 5, 6, 7], and summed. The variadic parameter is typed int, so every collected value must be an integer.
Output:
6
22
When the spread array has string keys, PHP 8.1 and later treat them as named arguments -- so total(...['nums' => 1]) would target a parameter called nums -- which is powerful but couples the array's keys to the function's parameter names, a point the next section makes concrete.
The third role of the dots: first-class callables
PHP 8.1 gave ... a third job. Writing a function's name followed by (...) -- with the literal three dots and nothing else in the parentheses -- does not call the function; it captures it as a Closure you can store in a variable and call later. This first-class callable syntax replaces the old, error-prone string and array forms such as 'total' or [$obj, 'method'] with a form the editor and the type checker both understand.
<?php
function total(int ...$nums): int
{
return array_sum($nums);
}
$sum = total(...); // capture, do not call -- $sum is now a Closure
echo $sum(10, 20), "\n"; // call it later like any closure
echo $sum(3, 4, 5, 6), "\n";
total(...) captures total as a closure without invoking it, so $sum can be passed to array_map, stored in a table of handlers, or called directly as here. The captured closure keeps the original's variadic signature, so it still accepts any number of integers.
Output:
30
18
This is the same ... token seen collecting and spreading, now in a capturing role, and it is the modern, refactor-safe way to refer to a function as a value.
Real World Example: A Paint Formula Sheet
A tinting station stores each colour as a formula -- an associative array naming the shots of each colorant -- and mixes a tin by spreading that formula into a mix function as named arguments. Any colorant the formula omits defaults to zero. The program below mixes three colours and prints a formula sheet with the total shots and how many colorants each uses.
<?php
declare(strict_types=1);
function mix(
string $name,
int $white = 0,
int $black = 0,
int $red = 0,
int $yellow = 0
): array {
$shots = $white + $black + $red + $yellow;
$used = count(array_filter([$white, $black, $red, $yellow], fn(int $n) => $n > 0));
return ['name' => $name, 'shots' => $shots, 'used' => $used];
}
$formulas = [
['name' => 'Ivory', 'white' => 40, 'yellow' => 3],
['name' => 'Slate', 'white' => 20, 'black' => 12],
['name' => 'Terracotta', 'white' => 15, 'red' => 18, 'yellow' => 6],
];
echo "FORMULA SHEET\n";
echo str_repeat('-', 30), "\n";
printf("%-12s %6s %10s\n", 'NAME', 'SHOTS', 'COLORANTS');
foreach ($formulas as $formula) {
$result = mix(...$formula);
printf("%-12s %6d %10d\n", $result['name'], $result['shots'], $result['used']);
}
Output:
FORMULA SHEET
------------------------------
NAME SHOTS COLORANTS
Ivory 43 2
Slate 32 2
Terracotta 39 3
The design reads beautifully: each formula is a self-describing card, mix(...$formula) spreads it in as named arguments so 'white' => 40 lands on the $white parameter regardless of order, and omitted colorants fall to their zero defaults. Ivory uses two colorants for forty-three shots; Terracotta uses three. Adding a new colour is one row, and the code that mixes it does not change.
But the spread hides a real fragility, and it is worth stating exactly. mix(...$formula) requires every key in the formula array to be the name of a parameter. Every formula here is clean, so it works -- but the moment a formula picks up an extra field, say 'sheen' => 'matte' for the shop's own records, the call throws Error: Unknown named parameter $sheen and the whole sheet crashes. The code silently assumes the data's keys and the function's parameter names are one and the same set, which is safe for hand-written literals but dangerous the day these formulas come from a database or a spreadsheet import that carries extra columns. It also means renaming a parameter -- $yellow to $amber -- silently breaks every stored formula, because named unpacking couples the caller's data to the callee's parameter names. The fix is to not spread untrusted arrays blindly: pull out the known keys explicitly, or accept a single array $formula parameter and read the colorants from it, so extra fields are ignored rather than fatal.
Common Mistakes
- Transposing positional arguments. Passing
f(30, 12)when the function expectsf($width, $height)in the other order produces a valid-looking wrong result with no error, because both values are the right type. Use named arguments when the parameters are easy to confuse.
- Placing a positional argument after a named one. Writing
f(white: 30, 12)is a parse error; every positional argument must precede the first named argument. Put the positionals first, then switch to names.
- Repeating defaults just to reach a later parameter. With positional passing you must supply
f('OK', 10, '-')to change only the pad, restating the default10. Use a named argument --f('OK', pad: '-')-- to skip straight to the one you want.
- Spreading an array whose keys do not match parameter names.
f(...$data)throwsUnknown named parameterif$datahas a key that is not a parameter. Only spread arrays you control, or read known keys out explicitly first.
- Putting the variadic parameter anywhere but last. A
...$restparameter must be the final one in the signature; nothing can follow it, because it consumes all remaining arguments. Declaring a parameter after it is a fatal error.
- Assuming a variadic is always an array you can index safely. Inside the function
...$numsis an array, but it may be empty if the caller passed nothing. Guard against the empty case rather than assuming at least one element.
- Over-using named arguments for one- or two-parameter calls. Naming both arguments of
max(a: 3, b: 5)adds noise without clarity. Reserve named arguments for calls where the names genuinely aid the reader -- many parameters, booleans, or skipped defaults.
- Forgetting that named arguments couple callers to parameter names. Renaming a parameter is a breaking change for any caller using it by name, including array spreads. Treat public parameter names as part of the API and rename them deliberately.
- Mutating a variadic and expecting the caller to see it. The collected array is a fresh array local to the function; changing it does not affect the caller's values. Return a new value rather than expecting the variadic to write back.
Best Practices
- Use named arguments when a call has several optional parameters, boolean flags, or a default you want to skip past, so the call site documents itself.
- Keep positional passing for short signatures with an obvious, hard-to-muddle order, such as
pow($base, $exp).
- Declare the variadic parameter last and give it a type, so every collected argument is checked and the signature stays valid.
- Prefer accepting a typed
arrayor a dedicated value object over a long list of positional parameters when a function needs many related inputs.
- Only spread arrays whose keys you control into a call; for external data, extract the known keys explicitly so an extra field cannot crash the call.
- Treat public parameter names as part of your API, since callers may depend on them by name, and rename them only as a deliberate breaking change.
- Put required parameters first and optional ones after, so both positional and named calls read naturally.
- Guard a variadic against the empty case rather than assuming the caller supplied at least one value.
Practice Exercises
- Write a function
box(string $text, int $padding = 1, string $border = '*'): stringand call it three ways: fully positional, with a named argument to set only the border, and with a named argument to set only the padding. Confirm each call takes the intended defaults for the arguments you omitted.
- Write a variadic
average(float ...$values): floatthat returns the mean of its arguments, and call it both with separate arguments and by spreading an array. Then call it with no arguments and add a guard so it returns0.0instead of dividing by zero.
- Take the paint formula example and make it robust: change
mixto accept a singlearray $formulaand read the known colorants out of it, then add a'sheen'field to one formula and confirm the sheet no longer crashes. Explain why this is safer than spreading.
- Write a function with three optional parameters and demonstrate the parse error from placing a positional argument after a named one, then fix the call by reordering. Explain the rule that positional arguments must precede named arguments.