Spread and named arguments in PHP
Modern call sites: pick arguments by name, unpack them from arrays.
<?php
function volume(int $length, int $width, int $height = 1): int {
return $length * $width * $height;
}
// named arguments skip the defaults you do not care about
echo volume(4, 3, height: 2), "\n";
echo volume(width: 5, length: 2), "\n";
// ...spread unpacks an array into positional arguments
$dims = [3, 4, 5];
echo volume(...$dims), "\n";
function sum(int ...$nums): int {
return array_sum($nums);
}
echo sum(1, 2, 3, 4), "\n";
How it works
height: 2targets one parameter by name and skips the rest.- Named arguments can arrive in any order the caller likes.
...$dimsspreads an array across the positional parameters.- In a signature,
int ...$numscollects any number of arguments instead.
Keywords and builtins used here
array_sumechofunctionreturnsumvolume
The run, in numbers
- Lines
- 17
- Characters to type
- 438
- Tokens
- 108
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 86 seconds.
Step 3 of 3 in Functions, step 12 of 27 in Language basics.