You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHPStan报错:模板类型T仅用于返回类型,未在参数中引用

解决PHPStan模板类型未在参数中引用的问题

PHPStan提示模板类型T未在参数中引用,核心原因是方法级的模板类型必须建立输入与输出的类型关联——模板类型的作用是让PHPStan能根据调用时传入的参数,推断出返回值的具体类型。如果模板类型只出现在返回值里,PHPStan没有任何输入信息来确定T到底对应哪个Searchable子类,自然会判定这个模板定义无效。

解决方案1:通过参数传递模板类型信息

如果T的类型和传入的参数相关(比如某个参数指定了Searchable子类),可以添加一个class-string<T>类型的参数,让PHPStan能通过该参数推断T的具体类型:

/**
 * @phpstan-template T of Searchable
 *
 * @param class-string<T>       $searchableClass // 新增参数,指定T对应的类
 * @param string                $indexName
 * @param ?array<string, mixed> $config
 *
 * @phpstan-return IndexResponse<T>
 *
 * @throws SearchEngineException
 */
public function createIndex(string $searchableClass, string $indexName, ?array $config): IndexResponse;

调用时传入具体的Searchable子类:

// PHPStan会推断返回值为IndexResponse<ProductSearchable>
$engine->createIndex(ProductSearchable::class, 'products', []);

解决方案2:固定返回类型(无需模板)

如果该方法的返回类型是固定的(比如始终返回某一种Searchable的IndexResponse),直接移除模板类型,指定具体的返回类型即可:

/**
 * @param string                $indexName
 * @param ?array<string, mixed> $config
 *
 * @phpstan-return IndexResponse<ProductSearchable> // 指定具体类型
 *
 * @throws SearchEngineException
 */
public function createIndex(string $indexName, ?array $config): IndexResponse;

解决方案3:将模板类型移至接口级别

如果整个SearchEngine接口的实现类都对应某一类Searchable,可以把模板类型定义在接口层面,而非单个方法:

/**
 * @phpstan-template T of Searchable
 */
interface SearchEngine
{
    /**
     * @param string                $indexName
     * @param ?array<string, mixed> $config
     *
     * @phpstan-return IndexResponse<T>
     *
     * @throws SearchEngineException
     */
    public function createIndex(string $indexName, ?array $config): IndexResponse;
}

实现接口时指定具体的T类型:

/**
 * @phpstan-implements SearchEngine<ProductSearchable>
 */
class ProductSearchEngine implements SearchEngine
{
    // 实现方法时,PHPStan会自动识别返回值为IndexResponse<ProductSearchable>
    public function createIndex(string $indexName, ?array $config): IndexResponse
    {
        // ...
    }
}

内容的提问来源于stack exchange,提问作者Wolfone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 12:52:55