phpstan:: Method (methodname)返回类型与泛型接口(interfacename)没有指定其类型



我已经为有序列表定义了一个接口。类docblock看起来像这样:

/**
* Interface ListOrderedInterface
* @template ListOrderedElement
*/

在该接口的方法docblock中,listderedelement用于确保添加到列表中的内容的类型是一致的。PHPStan在listderedinterface .php上运行干净。到目前为止一切顺利。

接下来,我为制造有序列表的工厂定义了一个接口。定义如下:

/**
* Class ListFactoryInterface
*/
interface ListOrderedFactoryInterface
{
/**
* makeList
* @return ListOrderedInterface
*/
public function makeList(): ListOrderedInterface;
}
phpstan:: Method makeList return type with泛型接口listderedinterface没有指定它的类型我不知道如何为接口指定类型。

谢谢你的帮助。

您需要在@return部分的makeList phpdoc中为您的listderedinterface提供专门化。

interface ListOrderedFactoryInterface
{
/**
* This is an example with a concrete type, syntax is <type>
* @return ListOrderedInterface<string>
*/
public function makeList(): ListOrderedInterface;
}

如果你也需要这个泛型,你还需要在工厂上添加@template,并从makeList返回一个泛型类型。

/**
* @template T
*/
interface ListOrderedFactoryInterface
{
/**
* @return ListOrderedInterface<T>
*/
public function makeList(): ListOrderedInterface;
}

在实现FactoryInterface的类中,添加@implements phpdoc。

/**
* Instead of string put the actual type it should return
* @implements ListOrderedFactoryInterface<string>
*/
class ConcreteFactory implements ListOrderedFactoryInterface
{
}
您可以在官方文档中找到更多示例:https://phpstan.org/blog/generics-by-examples

最新更新