PHPStorm:对于对象集合的正确 PHPDoc?

2022-08-30 13:34:09

我正在使用PHPStorm IDE,并且在运行代码检查时遇到了麻烦。

我有一个返回对象集合的方法。它本身就是一个对象,它有自己的方法,并实现了可遍历接口:Collection

class Repository
{
    public function findByCustomer(Customer $user)
    {
        // ...
        return new Collection($orders);
    }
}

如果我的文档返回一个,代码检查理解这个对象上的方法,但不了解集合包含哪些对象:findByUser()Collection

/**
 * @return Collection
 */
public function findByCustomer() { ... }

Method getTotal() not found in class Collection

如果我通过文档返回对象集合,代码检查现在了解集合中的内容,但不会了解其本身的方法:findByUser()OrderCollection

/**
 * @return Order[]
 */
public function findByCustomer() { ... }

Method slice() not found in class Order[]

有没有办法同时指定两者,就像Java的语法一样?

/**
 * @return Collection<Order>
 */
public function findByCustomer() { ... }

答案 1

您可以将它们(两种类型)组合在一起。在某些情况下可能并不理想,但可以工作,您可能会认为它比通过PHPDoc注释手动指定类型更好。@var

/** @return Collection|Order[] */

答案 2

从 2021.2 开始的 Phpstorm 允许以下语法:

/**
 * @return Collection<Order>
 */

来自PhpStorm What's New 2021.2的屏幕截图:
Screenshot from PhpStorm What's New 2021.2


推荐