Error Identifier: method.shadowTemplate
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);
/**
* @template T of \Exception
*/
class ErrorHandler
{
/**
* @template T
* @param T $value
* @return T
*/
public function handle($value)
{
return $value;
}
}
Why is it reported? #
A method declares a @template type parameter with the same name as one already declared on its containing class. The method-level template type T shadows the class-level template type T, which makes it impossible to reference the class template type from within the method. This is confusing and likely a mistake.
In the example above, the class declares @template T of \Exception, but the method also declares @template T (without the bound). Inside the method, T refers to the method’s template type, not the class-level one.
How to fix it #
Rename the method-level template type to avoid the conflict:
<?php declare(strict_types = 1);
/**
* @template T of \Exception
*/
class ErrorHandler
{
/**
- * @template T
- * @param T $value
- * @return T
+ * @template U
+ * @param U $value
+ * @return U
*/
public function handle($value)
{
return $value;
}
}
If the method intends to use the class-level template type, remove the @template declaration from the method:
/**
* @template T of \Exception
*/
class ErrorHandler
{
/**
- * @template T
* @param T $value
* @return T
*/
public function handle($value)
{
return $value;
}
}
How to ignore this error #
You can use the identifier method.shadowTemplate to ignore this error using a comment:
// @phpstan-ignore method.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: method.shadowTemplate
Rules that report this error #
- PHPStan\Rules\Generics\MethodTemplateTypeRule [1]