Error Identifier: method.templateTypeNotInParameter
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 Factory
{
/**
* @template T of object
* @param string $class
* @return T
*/
public function create(string $class): object
{
return new $class();
}
}
Why is it reported? #
A template type declared on a method is not referenced in any of its parameters. PHPStan cannot infer the concrete type for the template type T from the call site because no parameter uses it. This means the generic type information is useless – callers will always get the upper bound of the template type instead of a specific type.
In the example above, T appears in the @return tag but not in any @param tag. PHPStan has no way to determine what T should be when the method is called.
How to fix it #
Reference the template type in a parameter so PHPStan can infer it from the argument:
<?php declare(strict_types = 1);
class Factory
{
/**
* @template T of object
- * @param string $class
+ * @param class-string<T> $class
* @return T
*/
public function create(string $class): object
{
return new $class();
}
}
If the template type is genuinely not needed, remove it:
<?php declare(strict_types = 1);
class Factory
{
/**
- * @template T of object
- * @param string $class
- * @return T
+ * @param class-string $class
+ * @return object
*/
public function create(string $class): object
{
return new $class();
}
}
How to ignore this error #
You can use the identifier method.templateTypeNotInParameter to ignore this error using a comment:
// @phpstan-ignore method.templateTypeNotInParameter
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.templateTypeNotInParameter
Rules that report this error #
- PHPStan\Rules\Functions\ExistingClassesInArrowFunctionTypehintsRule [1]
- PHPStan\Rules\Functions\ExistingClassesInClosureTypehintsRule [1]
- PHPStan\Rules\Functions\ExistingClassesInTypehintsRule [1]
- PHPStan\Rules\Methods\ExistingClassesInTypehintsRule [1]
- PHPStan\Rules\Properties\ExistingClassesInPropertyHookTypehintsRule [1]