Sergey Telshevsky
Sergey Telshevsky

Reputation: 12197

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

Upvotes: 1

Views: 308

Answers (2)

LazyOne
LazyOne

Reputation: 165178

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

Upvotes: 2

Kris
Kris

Reputation: 41837

What you seem to want cannot really be done (at the moment) as far as I am aware. I've tried to get the same functionality myself some time ago.

However, you can do something like this:

<?php

/**
 * @return MyCollectionType
 */
function getEntityCollectionFromSomewhere()
{
    return ...
}

$myEntityCollection = getEntityCollectionFromSomewhere();

foreach($myEntityCollection as $entity)
{
    if ($entity instanceof MyEntityType)
    {
        // code completion is active here for MyEntityType...
    }
}

This is the best I've found so far; you get Collection completion where you're working with a collection, and entity functionality where you're working with a single element from that collection.

Upvotes: 1

Related Questions