Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically passing multiple typehinted objects into the constructor of a class in PHP 7

Tags:

php

php-7

Say I'm typehinting a series of values to an interface in the constructor of a class:

<?php

use Interfaces\Item;

class MyClass
{
    public function __construct(Item ...$items)
    {
        // Do stuff
    }
}

I can pass these items in manually easily enough:

$myclass = new MyClass($item1, $item2);

But I'm struggling to get it working more dynamically - the following doesn't work because it expects to receive multiple instances of Item rather than an array, so it raises a TypeError:

$items = [
    $item1,
    $item2
];
$myclass = new MyClass($items);

I can't think of a way of dynamically building the items I want to pass through when constructing the new class without changing it to expect an array, and I'd rather not do that because typehinting will obviously catch any objects passed through that shouldn't be. Can anyone see how I might achieve this?

like image 718
Matthew Daly Avatar asked Sep 15 '25 01:09

Matthew Daly


1 Answers

The splat operator (...) works two ways - you can use it in the function definition as you already have, but you can also use it to unpack an array of items into function arguments.

Try:

$myclass = new MyClass(...$items);

See https://eval.in/927133 for a full example

like image 135
iainn Avatar answered Sep 17 '25 15:09

iainn