user1544337
user1544337

Reputation:

How to document an array of [type]?

Say I have a function like this:

function theFunction() {
    $arr = array();
    for ($i=0;$i<10;$i++) {
        $arr[] = new theObject($i);
    }
    return $arr;
}

I need to document the return type of the function. I could of course just usearray, but that does not provide all the information that can be provided, and doesn't tell the developer much about the true nature of the function.

How do I document the type "array of [type]" in PHPDoc?

Upvotes: 12

Views: 16533

Answers (5)

Ivan Buttinoni
Ivan Buttinoni

Reputation: 4145

Array of array with of 2 element:

  1. key "priority" value type int
  2. key "service" value type string
/** @return array<array{priority: int, service: string}>  */

Upvotes: 1

SamGoody
SamGoody

Reputation: 14468

In PHP 7.4+ you can use type declarations to enforce the return type of a method.

While this is not meant for documentation, it does a better job of documenting than phpDocs did.

In your case, you can do:

function theFunction(): array {
    return [];
}

Upvotes: -1

Wilt
Wilt

Reputation: 44326

In PHPDoc you can do the following for type hinting array members:

@var array<\My\Folder\ClassName>

UPDATE

You can also explicitly declare the key for associative arrays as follows:

@var array<string, \My\Folder\ClassName>

And according to the answer posted here you can even explicitly declare the keys in case you would like to do so like this:

/**
 * @return array[
 *  'controller' => string,
 *  'action' => string
 * ]
 */

Note: This is tested and works perfectly well in PHP storm:

enter image description here

Upvotes: 8

Robert
Robert

Reputation: 20286

From the documentation of phpDocumentor

The value represented by Type can be an array. The type MUST be defined following the format of one of the following options:

  1. unspecified, no definition of the contents of the represented array is given. Example: @return array

  2. specified containing a single type, the Type definition informs the reader of the type of each array element. Only one Type is then expected as element for a given array.

    Example: @return int[]

    Please note that mixed is also a single type and with this keyword it is possible to indicate that each array element contains any possible type.

  3. specified containing multiple types, the Type definition informs the reader of the type of each array element. Each element can be of any of the given types. Example: @return (int|string)[]

    Note
    many IDEs probably do not support this notation yet.

Upvotes: 17

Dale
Dale

Reputation: 10469

If I'm remembering right you supply the return type and a description, can you not put it in the description?

/**
 * blah
 * @return array array of types
 */

Upvotes: -2

Related Questions