Ben*_*min 24 php phpdoc phpstorm
我正在使用PHPStorm IDE,并在运行代码检查时遇到麻烦.
我有一个返回对象集合的方法.它Collection本身就是一个对象,它有自己的方法,并实现了Traversable接口:
class Repository
{
public function findByCustomer(Customer $user)
{
// ...
return new Collection($orders);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我将文档findByUser()返回a Collection,则代码检查会理解此对象上的方法,但不了解该集合包含的对象:
/**
* @return Collection
*/
public function findByCustomer() { ... }
Run Code Online (Sandbox Code Playgroud)

如果我记录findByUser()返回一个Order对象集合,代码检查现在可以理解集合中的内容,但不了解Collection自身的方法:
/**
* @return Order[]
*/
public function findByCustomer() { ... }
Run Code Online (Sandbox Code Playgroud)
![在Order []类中找不到方法slice()](https://i.stack.imgur.com/ZTFSU.png)
有没有办法同时指定两者,像Java的语法?
/**
* @return Collection<Order>
*/
public function findByCustomer() { ... }
Run Code Online (Sandbox Code Playgroud)
Laz*_*One 43
您可以将它们(两种类型)组合在一起.在某些情况下可能并不理想,但有效并且您可能认为它比通过@varPHPDoc注释手动指定类型更好.
/** @return Collection|Order[] */
Run Code Online (Sandbox Code Playgroud)
小智 36
从 2021.2 开始,Phpstorm 允许使用以下语法:
/**
* @return Collection<Order>
*/
Run Code Online (Sandbox Code Playgroud)
这适用于 Doctrine Collections - 以及从 Laravel 9 开始的所有 Laravel Collections(L8 中不存在所需的注释)。
| 归档时间: |
|
| 查看次数: |
6132 次 |
| 最近记录: |