Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

408
Views
How to typehint generators in php?

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).

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Like other collections over phpdoc

/**
* @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');
};
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!