Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
class Foo
{
/**
* @template K of string
* @param array<K of 'a'|'b', list<K>> $values
*/
public function doFoo(array $values): void
{
}
}
Why is it reported? #
An array type can declare its own template type in its key, as in array<K of 'a'|'b', list<K>> or array{a: int, ...<K of string, list<K>>}. The value type can then refer to the specific key being accessed. See General arrays for details.
In the example above, the array key declares a template named K, but the method already has a @template K. Inside the array type, K now refers to the key template, not to the method’s template, so it’s unclear which one is meant. The same applies when the name collides with a @template of the enclosing class, or with a template declared by an enclosing callable or array type.
How to fix it #
Rename the template declared by the array key so it does not collide with templates already in scope:
/**
* @template K of string
- * @param array<K of 'a'|'b', list<K>> $values
+ * @param array<TKey of 'a'|'b', list<TKey>> $values
*/
public function doFoo(array $values): void
{
}
If the array is supposed to use the enclosing template instead of declaring a new one, drop the of bound from the key. A key without of, such as array<K, list<K>>, refers to the existing template:
/**
* @template K of string
- * @param array<K of 'a'|'b', list<K>> $values
+ * @param array<K, list<K>> $values
*/
public function doFoo(array $values): void
{
}
How to ignore this error #
You can use the identifier arrayKey.shadowTemplate to ignore this error using a comment:
// @phpstan-ignore arrayKey.shadowTemplate
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: arrayKey.shadowTemplate