Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use array as … type?

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 Symfony\Component\Mime\Address|string, array given

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Even if it’s with [] :

enter image description here

How can I use array as parameters?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading