0

What is the real purpose of function with ellipsis in its parameter?

I have this function:

class Dog{
    public function type(...$numbers){
        var_dump($numbers);
    }
}

and this function

class Dog{
    public function type($numbers){
        var_dump($numbers);
    }
}

Whether I put ellipsis or not, if I call the type function putting multiple parameters in it, its type will always be an array.

So my question is, why exactly should I put the ellipsis inside the parameter of a function?

Sidney Sousa
  • 3,378
  • 11
  • 48
  • 99
  • The type depends on how you call it in the second. How are you calling your functions? – Progrock Mar 09 '19 at 20:32
  • How do you call this function with multiple arguments? – Sindhara Mar 09 '19 at 20:32
  • its called a variadic see- http://php.net/manual/en/migration56.new-features.php#migration56.new-features.variadics – ArtisticPhoenix Mar 09 '19 at 20:34
  • 1
    It can be useful for things like this `$array = [[1,'a'],[2,'b'],[3,'c'],[4, 'b']]; print_r(array_merge(...$array));` output `[1,'a',2,'b',3,'c',4,'d']` especially if you don't know how long `$array` is. here is a better link http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list In the past we had to use things like `func_get_args()` and `call_user_func_array('function', $args)` etc. which is pretty ugly compared to this `...` – ArtisticPhoenix Mar 09 '19 at 20:38

1 Answers1

1

It's just syntactic sugar, called variable-length argument lists. It lets you pass the function multiple arguments that it will turn into an array automatically. In that example, it would let you call type(1, 2, 3) and $numbers would be an array of those three numbers.