Three points in the parameter of a function in a class, what is it?

6

I was inspecting a class from a phpoffice vendor called phpspreadsheet and found the following function in the Calculation.php module ... not a problem, but I would like to understand the meaning of this function, I have programmed it in php for 10 years and never had seen 3 points within the parameter of a function. I wonder what this means, what causes it or what it is for! Follow the function

private static function mkMatrix(...$args)
{
    return $args;
}
    
asked by anonymous 02.02.2018 / 13:50

2 answers

10

Since 5.6 has been implemented in function arguments as ... , known as spread operator . This means that the function / method will receive a variable amount of arguments and treat it as a array .

See:

function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);

The return of this function will be

10

You can also use to transform an array / tranversable into a list:

function add($a, $b) {
    return $a + $b;
}

echo add(...[1, 2])."\n";

$a = [1, 2];
echo add(...$a);

@edit

In previous versions, up to 5.5 , when passing a variable amount of parameters into a function, they were handled using the functions func_num_args , func_get_arg , func_get_args

Source: Function Arguments

    
02.02.2018 / 13:57
0

Since PHP 5.6 you can also use the% with% notation:

varied functions can now be implemented using ...$numbers operator instead of relying on func_get_args ().

function f($req, $opt = null, ...$params) {
    // $params is an array containing the remaining arguments.
    printf('$req: %d; $opt: %d; number of params: %d'."\n",
           $req, $opt, count($params));
}

f(1);
f(1, 2);
f(1, 2, 3);
f(1, 2, 3, 4);
f(1, 2, 3, 4, 5);

The above example will be displayed:

$ req: 1; $ opt: 0; número de params: 0
$ req: 1; $ opt: 2; número de params: 0
$ req: 1; $ opt: 2; número de params: 1
$ req: 1; $ opt: 2; número de params: 2
$ req: 1; $ opt: 2; número de params: 3

source: link

    
02.02.2018 / 14:06