'PHP Fatal error: Cannot use positional argument after argument unpacking
Task
I would like to write a function with variable number of parameters (using ...) that calls another function with the same arguments and a new one at the end. Order is important! The example below is just for demonstration.
What have I tried
function foo(...$params) {
$extraVariable = 6;
var_dump(...$params, $extraVariable);
}
foo(2, 4, 1, 4);
Problem
When I run it, I get the following error message:
PHP Fatal error: Cannot use positional argument after argument unpacking in /home/user/main.php on line 3
How can I achieve my goal?
Solution 1:[1]
tl;dr
Unpacking after arguments is not allowed by design, but there are 2 workarounds:
Create an array from the new element and unpack that as Paul suggested:
function foo(...$params) { $extraVariable = 6; var_dump(...$params, ...[$extraVariable]); }Push the new element to the params:
function foo(...$params) { $extraVariable = 6; $params[] = $extraVariable; var_dump(...$args); }
Explanation
PHP simply doesn't support this. You can see the unit test that checks this behavior:
--TEST--
Positional arguments cannot be used after argument unpacking
--FILE--
<?php
var_dump(...[1, 2, 3], 4);
?>
--EXPECTF--
Fatal error: Cannot use positional argument after argument unpacking in %s on line %d
Solution 2:[2]
See the bolded word?
PHP Fatal error: Cannot use positional argument after argument unpacking in /home/user/main.php on line 3
So use it before unpacking.
var_dump($extraVariable, ...$params);
Solution 3:[3]
There is a workaround. You cannot use positional arguments after unpacked one, but you can use several unpacked arguments; so you can just wrap your variable(s) in array literal and unwrap it like this:
var_dump(...$params, ...[$extraVariable]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | AbraCadaver |
| Solution 3 | Edward Surov |
