Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

409
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda