Last active
September 3, 2023 23:40
-
-
Save Antnee/fb2c41b0e3cf65eadf0c to your computer and use it in GitHub Desktop.
PHP 7 Generator Return Type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It works for me @rhift