如何使用 psalm 和 phpstan 为工厂编写泛型

我正在尝试 phpstan 和 psalm for php,我想编写一个类,它可以接受不同类型的对象并根据要调用的工厂返回正确的对象。

我想要实现的是,如果我将类型 A 的对象传递给 Transformer,编译器知道将返回 SuperA。

虽然我可以在 psalm 中没有错误(尽管我仍然得到 SuperA|SuperB 而不是正确的对象),但我在 phpstan 中传递的内容出现了错误。

https://phpstan.org/r/4fce6f46-7aea-4f73-8259-df895910f064

https://psalm.dev/r/352e64ea95

有办法做到吗?


翻翻过去那场雪
浏览 41回答 1
1回答

慕桂英3389331

所以你想在A的基础上得到SuperA,在B的基础上得到SuperB。我将 A+SuperA 和 B+SuperB 连接在一起,如下所示:https:&nbsp;//phpstan.org/r/28e4e6ec-887b-4735-9b34-c034b4fa04ec/**&nbsp;* @template TSuper of Super&nbsp;*/interface Common{}/**&nbsp;* @implements Common<SuperA>&nbsp;*/&nbsp;class A implements Common{}/**&nbsp;* @implements Common<SuperB>&nbsp;*/&nbsp;class B implements Common{}interface Super{}class SuperA implements Super{&nbsp; &nbsp; public function callA(): void{}}class SuperB implements Super{&nbsp; &nbsp; public function callB(): void{}}然后工厂需要有这个签名:/**&nbsp;* @template T of Super&nbsp;* @param Common<T> $obj&nbsp;* @return T&nbsp;*/public function transform($obj)
打开App,查看更多内容
随时随地看视频慕课网APP