为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
翻翻过去那场雪 2024-01-19 15:54:14
我正在尝试 phpstan 和 psalm for php,我想编写一个类,它可以接受不同类型的对象并根据要调用的工厂返回正确的对象。我想要实现的是,如果我将类型 A 的对象传递给 Transformer,编译器知道将返回 SuperA。虽然我可以在 psalm 中没有错误(尽管我仍然得到 SuperA|SuperB 而不是正确的对象),但我在 phpstan 中传递的内容出现了错误。https://phpstan.org/r/4fce6f46-7aea-4f73-8259-df895910f064https://psalm.dev/r/352e64ea95有办法做到吗?
查看完整描述

1 回答

?
慕桂英3389331

TA贡献2036条经验 获得超8个赞

所以你想在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)


查看完整回答
反对 回复 2024-01-19
  • 1 回答
  • 0 关注
  • 32 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信