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

问题描述

我正在尝试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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...