Quantcast
Channel: User totymedli - Stack Overflow
Viewing all articles
Browse latest Browse all 54

Answer by totymedli for PHP Fatal error: Cannot use positional argument after argument unpacking

$
0
0

tl;dr

Unpacking after arguments is not allowed by design, but there are 3 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);  }
  • If the wrapped function has named params, just add the extra argument as a named one as James suggested:

      // needs PHP 8.1  function foo(...$params) {      $extraVariable = true;      array_search(...$params, strict: $extraVariable);  }

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--<?phpvar_dump(...[1, 2, 3], 4);?>--EXPECTF--Fatal error: Cannot use positional argument after argument unpacking in %s on line %d

Viewing all articles
Browse latest Browse all 54

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>