phpDoc notation to specify return type identical t

2019-04-09 05:34发布

问题:

Imagine the following hypothetical class structure, not an all too uncommon scenario with all PHPdoc hinting set up correctly:

class BaseFilter {
  /** ...base methods... */
}

class TextFilter extends BaseFilter {
  public function setMinLength($len)
  {
    /** ...irrelevant */
  }
}

class SomethingWithFilters
{
  /**
   * @param BaseFilter $filter A valid filter to be added.
   * @return BaseFilter The filter that was added for easy chaining
   */
  public function addFilter(BaseFilter $filter)
  {
    $this->filters[] = $filter;
    return $filter;
  }

  /** @var BaseFilter[] A list of filters */
  private $filters = [];
}

Now I use this code as follows:

$myClass = new SomethingWithFilters();
$myClass->addFilter(new TextFilter())->setMinLength(8);

In phpStorm (and probably most other IDEs since it makes sense) the second line produces a warning, stating that BaseFilter does not contain a method setMinLength. While absolutely correct, this is intended polymorphism behaviour, fully utilizing PHP's late binding characteristics - in a language like C# you'd have to upcast explicitly. As such I would expect phpDoc syntax to support some kind of dynamic notation here, stating that the return type for addFilter is identical to the $filter type supplied.

I have tried changing it to:

@return $filter

But this just shows up as a reference to BaseFilter and is treated as such, still giving the warning.

Is there any standardized way to achieve this effect, in such a way that at least the common IDEs can understand it?

回答1:

Probably the best an IDE could do here would be if your @return on addFilter() actually listed all the possible BaseFilter children that could be returned:

@return BaseFilter|TextFilter|AnotherFilter

This might trigger your IDE into providing all the possible methods for all those possible return classes. It depends on whether or not the IDE in use knows how to recognize such a list of possible return types. Obviously this would get tedious on your part though, putting such a list in many return tags.

I do not know of any IDE that would look at your return type of BaseFilter alone, generate a list of all possible parent+child methods, and thus make that whole list available for autocompletion automagically.