[英]How to write generics for factories using psalm and phpstan
I'm trying out phpstan and psalm for php and I would like to write a class that can take different type of objects and return the right one based on the factory to call.我正在为 php 尝试 phpstan 和 psalm,我想编写一个可以接受不同类型对象并根据要调用的工厂返回正确对象的类。
What I'm trying to achieve is that if I pass an object of type A to the Transformer, the compiler knows that a SuperA will be returned.我想要实现的是,如果我将 A 类型的对象传递给 Transformer,编译器知道将返回 SuperA。
While I can go without errors in psalm (though I still get SuperA|SuperB instead of the right object), I got an error on what I'm passing in phpstan.虽然我可以在 psalm 中没有错误(尽管我仍然得到 SuperA|SuperB 而不是正确的对象),但我在 phpstan 中传递的内容出现错误。
https://phpstan.org/r/4fce6f46-7aea-4f73-8259-df895910f064 https://phpstan.org/r/4fce6f46-7aea-4f73-8259-df895910f064
https://psalm.dev/r/352e64ea95 https://psalm.dev/r/352e64ea95
Is there a way to do it?有没有办法做到这一点?
So you want to get SuperA based on A and SuperB based on B.所以你想得到基于 A 的 SuperA 和基于 B 的 SuperB。
I'd connect A+SuperA and B+SuperB together like this: https://phpstan.org/r/28e4e6ec-887b-4735-9b34-c034b4fa04ec我会像这样将 A+SuperA 和 B+SuperB 连接在一起: https ://phpstan.org/r/28e4e6ec-887b-4735-9b34-c034b4fa04ec
/**
* @template TSuper of Super
*/
interface Common
{
}
/**
* @implements Common<SuperA>
*/
class A implements Common
{
}
/**
* @implements Common<SuperB>
*/
class B implements Common
{
}
interface Super
{
}
class SuperA implements Super
{
public function callA(): void{}
}
class SuperB implements Super
{
public function callB(): void{}
}
The factory then needs to have this signature:然后工厂需要有这个签名:
/**
* @template T of Super
* @param Common<T> $obj
* @return T
*/
public function transform($obj)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.