psalm 通过泛型类型参数(generic type parameters)让集合类保留元素的具体类型。在定义集合类时,使用 `

如何定义带泛型的集合类
要创建一个能保留元素类型的集合类,需要在类声明后添加泛型参数,例如 `@template T`。然后在类的属性或方法中使用这个模板变量。这样,当实例化该类并指定具体类型时,Psalm 就知道集合里装的是什么。

<?php
namespace App;
/**
* @template T
*/
class Collection {
/**
* @var array<T>
*/
private array $items;
public function __construct(array $items = []) {
$this->items = $items;
}
/**
* @return T|null
*/
public function first(): ?object {
return $this->items[0] ?? null;
}
}
/**
* @param Collection<string> $stringCollection
*/
function processStrings(Collection $stringCollection): void {
// Psalm 知道 first() 返回 string|null
$item = $stringCollection->first();
if ($item !== null) {
echo strtoupper($item); // 安全调用
}
}
$col = new Collection(["hello", "world"]);
processStrings($col);
如何在函数参数中约束集合类型
在函数或方法签名中,可以通过 `@param Collection

<?php
namespace App;
/**
* @template T
*/
class Item {
public function __construct(public string $name) {}
}
/**
* @template T
*/
class Container {
/**
* @var list<T>
*/
private array $data;
/**
* @param list<T> $data
*/
public function __construct(array $data) {
$this->data = $data;
}
/**
* @return T
*/
public function get(int $index) {
return $this->data[$index];
}
}
/**
* @param Container<Item> $itemContainer
*/
function getName(Container $itemContainer): string {
// Psalm 推断 get(0) 返回 Item 类型
$item = $itemContainer->get(0);
return $item->name;
}
$container = new Container([new Item("Test")]);
echo getName($container);
当集合为空时 Psalm 如何处理类型
当集合可能为空或访问不存在的索引时,Psalm 会将返回类型标记为联合类型,通常包含 `null` 或抛出异常。开发者必须通过类型检查(如 `!== null`)或使用 `@throws` 注解来处理这些情况,以确保类型安全。


















