Assume you have a class like:
class MyClass
{
public function __construct(public int $id, public string $foo)
{
}
}
and a generator creating multiple instances of that class like this:
$myGenerator = function (): \Generator {
yield new MyClass(id: 21, foo: 'fnord');
yield new MyClass(id: 13, foo: 'baz');
yield new MyClass(id: 42, foo: 'Thanks for the fish');
};
How can I typehint a generator function so that it infers the type of each element during iteration?
foreach ($myGenerator as $instance) {
$instance-> // no autocompletion in IDE as type is not known
}
I don't want to do:
foreach ($myGenerator as $instance) {
/** @var MyClass $instance */
$instance-> // now autocomplete works inside an IDE
}
as it would pester each usage of the generator with redundant typehints. I want to provide it once at best on the level of the return type of the generator.
Is there a better alternative to typehint a generator?
In pseudo-code, I would expect of being able to do something along the lines of:
$myGenerator = function (): \Generator<MyClass> {...}
I assume php's type-system isn't up for this, I wouldn't mind using phpdocs / phpstan. Main use case is IDE support (in my case phpStorm though it should work beyond that).
Like other collections over phpdoc
/**
* @return \Generator<MyClass>
* or
* @return \Generator|MyClass[]
*/
$myGenerator = function (): \Generator {
yield new MyClass(id: 21, foo: 'fnord');
yield new MyClass(id: 13, foo: 'baz');
yield new MyClass(id: 42, foo: 'Thanks for the fish');
};
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