Is it possible for PhpStorm to infer the return type of this method?

不问归期 提交于 2019-12-13 19:46:20

问题


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';
}

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.


回答1:


Try this:

/**
 * @method \User getFirst()
 */
class UserCollection extends Collection
{
    protected static $requiredType = 'User';
}


来源:https://stackoverflow.com/questions/36217313/is-it-possible-for-phpstorm-to-infer-the-return-type-of-this-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!