phpvariadicphp-8

optional named argument after variadic argument


In PHP 7.x, I had some function that get array of parameters and then some flags.

a simplified sample:

<?php
    function sum($param, $min=0, $max=100)
    {
        $sum = 0;
        foreach ($param as $value)
            if ($value>=$min && $value<=$max)
                $sum += $value;
        return $sum;
    }

    echo sum([100, 10, 4], 0, 50);
?>

Now in PHP 8.1, I want to change function definition to variadic (unpack array), and function call to named arguments

so I changed the function definition to this:

    function sum(...$param, $min=0, $max=100)

and function call to this:

    echo sum(100, 10, 4, max:50);

But I got this error message:

Fatal error: Only the last parameter can be variadic in test.php on line 2

Any idea to solve?

TIA


Solution

  • You need to rewrite the order, so as the error says:

    the variadic parameter as last argument.

    function sum($min=0, $max=100, ...$param)