5

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?

totymedli
  • 26,417
  • 20
  • 126
  • 158
  • 4
    I would be thankful if the downvoters would point out the problems with my question. – totymedli Apr 11 '18 at 19:31
  • Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – emix Mar 31 '19 at 16:55
  • 3
    @emix How on Earth is this a duplicate of that? That thread doesn't contain anything even slightly related to argument unpacking. – totymedli Mar 31 '19 at 21:21

3 Answers3

12

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
totymedli
  • 26,417
  • 20
  • 126
  • 158
3

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);
AbraCadaver
  • 77,023
  • 7
  • 60
  • 83
1

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]);
Edward Surov
  • 339
  • 1
  • 2