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

如何在PHPStan中为collect方法标注toArray返回值的数组类型?

解决方案

在PHPStan里确实有办法实现这种类型复用,不用重复复制toArray的返回类型注解,主要有两种实用方式:

方式一:使用PHPStan内置的ReturnTypeOf工具类型

直接在collect方法的@return注解里引用toArray方法的返回类型,语法如下:

class ExampleClass {
    /**
     * @return array{
     *     id: int,
     *     image: string,
     *     name: string,
     *     ...etc...
     * }
     */
    protected function toArray() {
        return [/* 填充数据 */];
    }

    /**
     * @return list<ReturnTypeOf<self::toArray()>>
     */
    public function collect() {
        return [/* 多个toArray响应组成的数组 */];
    }
}

这里的list<>是PHPStan用来表示索引从0开始的连续整数索引数组的类型,ReturnTypeOf<self::toArray()>会自动获取toArray方法的返回类型,完美实现复用。

方式二:定义PHPStan类型别名

如果需要在更多地方复用这个数组类型,也可以先定义一个类型别名,再在两个方法里引用:

/**
 * @phpstan-type ItemArray array{
 *     id: int,
 *     image: string,
 *     name: string,
 *     ...etc...
 * }
 */
class ExampleClass {
    /**
     * @return ItemArray
     */
    protected function toArray() {
        return [/* 填充数据 */];
    }

    /**
     * @return list<ItemArray>
     */
    public function collect() {
        return [/* 多个toArray响应组成的数组 */];
    }
}

这种方式适合该类型需要在多个方法甚至多个类中复用的场景,维护起来更方便。

注意:ReturnTypeOf是PHPStan特有的工具类型,需要确保你的PHPStan版本支持(一般较新版本都支持),如果是旧版本可能需要升级。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 01:13:19