phpsplat

Pass PHP splat parameters to another function


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.


Solution

  • 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().