Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to annotate a class that can handle a/any generic class? #6656

Discussion options

I've set up the following contrived example to show my question:

https://phpstan.org/r/c35368f8-d6fa-4a1c-bb4a-555fa7972855

interface Collectable {}
/**
 * @template T of Collectable
 */
interface CollectionInterface {}
class Collector {
	public function collect(CollectionInterface $collection): void {}
}

This results in:

Method Collector::collect() has parameter $collection with generic interface CollectionInterface but does not specify its types: T

How do I annotate Collector to show it handles any CollectionInterface? I could add a /** @param CollectionInterface<Collectable> $collection */ to the collect method to satisfy the analysis, but this adds a noisy comment and no new information.

You must be logged in to vote

Yes, writing /** @param CollectionInterface<Collectable> $collection */ is the right way. You need to decide that and tell that to PHPStan, it can't assume that on your behalf. You can turn off this check with this setting: checkGenericClassInNonGenericObjectType: false (https://phpstan.org/config-reference#vague-typehints)

Replies: 1 comment 2 replies

Comment options

Yes, writing /** @param CollectionInterface<Collectable> $collection */ is the right way. You need to decide that and tell that to PHPStan, it can't assume that on your behalf. You can turn off this check with this setting: checkGenericClassInNonGenericObjectType: false (https://phpstan.org/config-reference#vague-typehints)

You must be logged in to vote
2 replies
Comment options

Ok, thanks. Can I do that for the entire class at once? Say it has a number of methods, all expecting or returning CollectionInterface<Collectable> where the type hint is CollectionInterface.

Comment options

You can make it shorter with local type aliases: https://phpstan.org/writing-php-code/phpdoc-types#local-type-aliases

Answer selected by leongersen
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Support
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /