1

If I have one PHP function which accepts splat parameters:

function1(...$parms1) {...}

and I call this function from another function which also accepts splat parameters:

function2(...$parms2) {function1($parms2);}

the invocation of function1 appears to wrap function2 parms into another array (i.e. function1 sees an array within an array).

Is there anyway of passing the parms from function2 to function1 as is, without the implicit creation of a second parameter array?

Don't get me wrong, I can see that PHP is doing precisely what I'm asking it to do, but it would be more convenient if I could pass function2's splat directly to function1.

Any advice would be very much appreciated.

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
PHPNoob
  • 57
  • 5
  • 2
    I think its wrong `function2(...$parms2) {function1($parms2);}`, you should call it `function2(...$parms2) {function1(...$parms2);}` – splash58 Sep 03 '19 at 14:37
  • How are you calling `function2()`? Something like `function2(1,2);` or `function2([1,2]);` – Nigel Ren Sep 03 '19 at 14:59
  • The accepted answer is 100% correct for the question. However, you should avoid this. It hides the parameters and required data types, which in turn voids the usefulness of IDEs and PHP data type checking etc. If that is something you don't care about (or have too many params) why not just pass an array in the first place? Or better yet, set some object and pass that. – James Jul 13 '22 at 11:27

1 Answers1

2

This way is pretty simple:

function2(...$parms2) {
    // stuff happens...
    // then call function1
    function1(...$parms2);
}

Splat works with calls as well.

Check the PHP documentation for function arguments. In example #14 you can see ... used to accept arguments as you're currently doing. In example #15 you can see it used to provide arguments as I showed here.

$parms2 is not some special kind of iterable specific to variable length arguments, it's just a normal array. That's why you're seeing the "array within an array" in function1(), but that also means it can be unpacked with ... when you use it to call function1().

Don't Panic
  • 41,125
  • 10
  • 61
  • 80