问题描述
我正在尝试PHPstan和psalm for PHP,我想编写一个可以接受不同类型对象并根据工厂调用返回正确对象的类。
我要实现的目标是,如果将类型A的对象传递给Transformer,则编译器知道将返回SuperA。
虽然我可以在诗篇中没有任何错误(尽管我仍然得到SuperA | SuperB而不是正确的对象),但我在PHPstan中传递的内容却出错了。
https://phpstan.org/r/4fce6f46-7aea-4f73-8259-df895910f064
https://psalm.dev/r/352e64ea95
有办法吗?
解决方法
因此,您希望获得基于A的SuperA和基于B的SuperB。
我将这样连接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{}
}
然后工厂需要具有此签名:
/**
* @template T of Super
* @param Common<T> $obj
* @return T
*/
public function transform($obj)