<?php
class Item {
private $id;
public function __construct(int $id)
{
$this->id = $id;
}
public function id() : int
{
return $this->id;
}
}
class Collection {
private $items = [];
public function __construct(Item ...$items)
{
$this->items = $items;
}
public function item() : Generator
{
yield from $this->items;
}
}
$items = [];
for ($i=0; $i<10; $i++) {
$items[] = new Item($i);
}
$collection = new Collection(...$items);
$generator = $collection->item();
printf("\nThe Collection::item() method returns a type of %s, as expected\n", get_class($generator));
printf("However, it yields the following:\n\n");
foreach ($generator as $item) {
printf("\tClass: %s. Calling id() method returns %d (%s)\n", get_class($item), $item->id(), gettype($item->id()));
}
printf("\n\nIt doesn't appear to be possible to hint the yielded type\n\n");