PhpStorm是否可以推断此方法的返回类型? [英] Is it possible for PhpStorm to infer the return type of this method?
问题描述
我想我可能需要在某个地方添加一个特殊的注释,但是我不由自主地意识到,PhpStorm足够聪明,可以解决给定笨拙的继承模式的返回类型.
I imagine I might need to add a special annotation somewhere, but I'm crossing my fingers that PhpStorm is smart enough to resolve return types given awkward inheritance patterns.
例如,我有一些类似于此的代码:
For example, I have some code that resembles this:
<?php
class Collection extends \ArrayObject
{
public function __construct(array $items)
{
foreach ($items as $key => $value) {
if (isset(static::$requiredType) && !$item instanceof static::$requiredType)
$this->offsetSet($key, $value);
}
}
public function getFirst()
{
return $this->offsetGet(0);
}
}
class MessageCollection extends Collection
{
protected static $requiredType = 'Message';
}
class UserCollection extends Collection
{
protected static $requiredType = 'User';
}
如果我调用UserCollection::getFirst()
时它推断返回了User
,而我调用MessageCollection::getFirst()
时它推断返回了Message
,则我想这样做.我可以在某处添加一些注释以实现此结果吗?
I'd like it if when I call UserCollection::getFirst()
it inferred that a User
was returned, while when I call MessageCollection::getFirst()
it inferred that a Message
was returned. Is there some annotation I could put in somewhere to achieve this result?
我的第一个想法是这样的:
My first thought was something like this:
/**
* @return Message|User|XXXX|YYYY|ZZZZ|AAAA|BBBB|CCCC|DDDD
*/
public function getFirst()
{
return $this->offsetGet(0);
}
但是我想当我添加更多的收集类时,这会变得毫无用处.
but I imagine that would get a little ridiculous to the point of being useless as I add more collection classes.
推荐答案
尝试一下:
/**
* @method \User getFirst()
*/
class UserCollection extends Collection
{
protected static $requiredType = 'User';
}
这篇关于PhpStorm是否可以推断此方法的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!