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

Asked

Viewed 743 times

7

I was inspecting a class of a phpoffice vendor called phpspreadsheet and found the following function in the module Calculation.php... is not really a problem, but I would like to understand the meaning of this function, I program in php at 10 years and have never seen 3 points within a function parameter. I would like to know what this means, what cause or what it serves! Follow the function

private static function mkMatrix(...$args)
{
    return $args;
}

2 answers

11


From the version 5.6 was implemented in the arguments from the function as ..., known as Operator spread. This means that the function/method will receive a variable amount of arguments and will treat it as a array.

Behold:

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 it to turn 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 the previous versions, up to the 5.5, by passing a variable amount of parameters in a function, they were treated using the functions func_num_args, func_get_arg, func_get_args

Source: Function arguments

0

Since PHP 5.6 you can also use the ...$numbers notation:

As variable functions can now be implemented using ... 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: http://docs.php.net/manual/en/migration56.new-features.php#migration56.new-Features.variadics

Browser other questions tagged

You are not signed in. Login or sign up in order to post.