MikO
MikO

Reputation: 18751

PHPDoc - Specify the type of array keys

How can I specify the type of the keys in the documentation of a PHP method that returns an array?


For example, I use this for an array of objects @return MyClass[].

But I want to comment an array like array( 'string' => array( MyClass ) ), is this possible?

Upvotes: 21

Views: 14823

Answers (3)

Nhat Ngo
Nhat Ngo

Reputation: 123

You can try to modify the format, it returns an array with special keys(lat, lng) with their types:

@return array{lat: float, lng: float}

Upvotes: 1

Emmanuel Guiton
Emmanuel Guiton

Reputation: 1445

Years after the question, it is possible to document array keys and values using, for example, @return array<integer, string> for an array of string values indexed by integer keys.

I do not know to what extent this syntax is standard and well supported. Tools such as PHPCS or Psalm do support it.

Upvotes: 28

user3734231
user3734231

Reputation: 36

Why would you need to specify the datatype. You can just access the values in the array by using a foreach to loop trough the results.

For example:

$arr = array("name" => "MikO", "street" => "straatnaam", "number" => "2");


//Here is key the first key, in this case: name, street, number
//And value are the values of the keys, in this case: MikO, straatnaam, 2

foreach($arr as $key => $value)
{
echo $key." ".$value."<br/>";
}

You can also extract some specific data out of it by using this:

echo $arr['name'];

If you want to go into the object:

foreach($arr as $objname => $objcontent)
{
 foreach($objcontent as $objnodename => $objnodevalue)
{
echo $objnodename." = ".$objnodevalue;
}

}

Upvotes: -18

Related Questions