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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With