例如,如果我有一个这样的课程:
class Foo
{
/**
* @var array<string, array{name: string, age: int}>
*/
private array $things;
/**
* @return array
*/
public function getThings(): array
{
return $this->things;
}
}
Run Code Online (Sandbox Code Playgroud)
然后 phpstan 会给我一些类似于Method Foo::getThings() return type has no value type specified in iterable type array.
当然,我可以通过将数组形状定义添加到 来解决这个问题@return,但考虑到我已经在属性上定义了这个,有没有办法避免我在这里缺少的重复?
不。PHPStan 不会像那样读取方法主体来了解它返回的内容。
您可以使用本地类型别名来减少重复:
/** @phpstan-type Things array<string, array{name: string, age: int}> */
class Foo
{
/**
* @var Things
*/
private array $things;
/**
* @return Things
*/
public function getThings(): array
{
return $this->things;
}
}
Run Code Online (Sandbox Code Playgroud)