Search code examples
phpphpstormphpdoc

PHPDoc container objects to act like arrays


Is it possible to indicate that an object behaves like a container, implements \ArrayAccess when writing a doc, specifically, a @return one.

For example if I have a class Collection implements \ArrayAccess, \Countable, \IteratorAggregate object filled with Entity objects from database.

What I'd like to have is PHPStorm (specifically) to have hints available for Collection objects as well as to understand what values they have.

Currently we have this notation for arrays of objects

/**
* @return \Entity[]
*/

This means the method returns an array of Entities. How may I do the same for a different class? I'm thinking about something like this:

/**
* @return \Entity[\Collection]
*/

I have created a pastebin (note that it has links to two more pastebins for Entity and Collection classes).

PASTEBIN example


Solution

  • Based on your pastebin examples single typehint in right place seems to be enough (tested in PhpStorm v9.5 EAP build):

    /** @var \Collection|\Entity[] $collection */
    $collection = new Collection($entities);
    

    For $collection it offers methods from \Collection class:

    enter image description here

    For $entity (inside foreach loop) it offers \Entity methods:

    enter image description here

    If anything you can always type hint $entity variable individually:

    enter image description here