Skip to content
Advertisement

PHPStorm: correct PHPDoc for a Collection of Objects?

I’m using the PHPStorm IDE, and run into trouble when I run the code inspection.

I have a method which returns a collection of objects. The Collection itself is an object, which has its own methods, and implements the Traversable interface:

class Repository
{
    public function findByCustomer(Customer $user)
    {
        // ...
        return new Collection($orders);
    }
}

If I document findByUser() to return a Collection, the code inspection understands the methods on this object, but doesn’t understand what objects the collection contains:

/**
 * @return Collection
 */
public function findByCustomer() { ... }

Method getTotal() not found in class Collection

If I document findByUser() to return a collection of Order objects, the code inspection now understands what’s inside the collection, but not the methods on the Collection itself:

/**
 * @return Order[]
 */
public function findByCustomer() { ... }

Method slice() not found in class Order[]

Is there a way to specify both at the same time, something like Java’s syntax?

/**
 * @return Collection<Order>
 */
public function findByCustomer() { ... }

Advertisement

Answer

Phpstorm starting from 2021.2 allows the following syntax:

/**
 * @return Collection<Order>
 */

Screenshot from PhpStorm What’s New 2021.2:
Screenshot from PhpStorm What's New 2021.2

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement