Splat Operator on function calls

Hi.
I’m creating a class where the constructor is supposed to get an array of objects.

class Foo{
   protected $property;
   public function __construct(MyObject ...$arrayOfMyObjects){
      $this->property = $arrayOfMyObjects;
   }
}

So I expect that Yii/PHP would validate $arrayOfMyObjects as an array with 1 or more MyObject instances.

But I’ getting the TypeError: … __construct() must be an instance of MyObject, array given, called in…

Is that the way to do this or what I have done that it is not working?

Thank you

This is not how ... operator works. __construct(MyObject ...$arrayOfMyObjects) means that constructor accepts any number (including zero) of arguments containing MyObject instance. So new Foo(), new Foo($myObject) or new Foo($myObject1, $myObject2). If you have array of objects, you need to use splat operator to unpack it to list of arguments: new Foo(...$myObjects).

2 Likes

Hi @rob006

Your answer makes perfect sense to me and following it, I could make it works.

Thank you so much.