Skip to content

PHPStan rejects @var static<string> on a factory result when the class implements IteratorAggregate #15796

Open
phpstan/phpstan-src
#7152

Description

@binaryfire

Bug report

Items<T> implements IteratorAggregate<int, T>. Its make() method creates a new collection from the values passed to it and returns static<U>, where U is the type of those values. When I pass a list of strings, PHPStan accepts the result as static<string> until I add an inline @var saying the same thing:

/** @return static<string> */
public function names(): static
{
    /** @var static<string> $names */
    $names = $this->make(['Alice']);
    return $names;
}

On line 34 PHPStan reports PHPDoc tag @var with type static(Items<string>) is not subtype of native type static(Items<T>). If I remove just the @var, PHPStan itself reports static(Items<string>) for $names with dumpType(). If I keep the annotation but remove the IteratorAggregate interface and its @implements and #[\Override] annotations, the example also passes. Implementing a generic custom interface (@implements Bag<T>) instead doesn't trigger it.

This passes on 2.3.2 and fails on 2.3.3, 2.3.7 and the current 2.3.x branch.

Code snippet that reproduces the problem

Run the collection example in the PHPStan Playground.

Expected output

No errors. The new collection holds strings regardless of what the original collection holds.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions