问题
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