skip to Main Content

I want to call a method like that:

public function to(Address|string ...$addresses) {}

I can call it with $obj->to("my-address"). But, when I want to give a list of address, I’m using:

$myList = [ "address-1", "address-2" ];
$obj->to($myList);

But I get this error: must be of type SymfonyComponentMimeAddress|string, array given

Even if it’s with [] :

enter image description here

How can I use array as parameters?

2

Answers


  1. You’re using ... to take every argument. You should spread your array before passing it to to():

    $myList = [ "address-1", "address-2" ];
    $obj->to(...$myList);
    
    Login or Signup to reply.
  2. You need to add ... in the call to the function as well. That syntax has two complementary meanings, both documented on the same page of the manual.

    • When used in the declaration of the function, as you have, it means "collect separate arguments (which must each be of the correct type, if specified) into an array"
    • When used in calling a function, it means "pass the items of this array as separate arguments"

    So:

    $myList = [ "address-1", "address-2" ];
    $obj->to(...$myList);
    

    Means the same as:

    $obj->to("address-1", "address-2");
    

    And then the ...$addresses in the function declaration makes that back into an array, checking that each item matches the type declaration Address|string.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search