YuraV
YuraV

Reputation: 103

phpdoc variable of class ArrayObject

I have a class that extends ArrayObject

class Collection extends ArrayObject

I know i can define array of objects using this code:

/* @var $userArray Model_User[] */

But how can i define variable $userArray as an custom array of class Collection that contains objects of class Model_User?

Without changing class Collection or its phpdoc. I want to use the same class Collection for different arrays of objects.

This is not the same as PHPDoc type hinting for array of objects?, because in that subject discussion is related to common arrays in php, which are phpdoced as /* @var $userArray Model_User[] */ in the mean time my question relates to custom build array which if phpdoced my method above will not type hint methods of custom build array class, like so $userArray->echoChanges() because it will think its a common array, not an array of class Collection. And yes $userArray also acts as an array, so it should type hint array contents $userArray[3]->name.

Upvotes: 0

Views: 1620

Answers (1)

Gerard Roche
Gerard Roche

Reputation: 6391

PSR-5: PHPDoc proposes a form of Generics-style notation.

Syntax

Type[]
Type<Type>
Type<Type[, Type]...>
Type<Type[|Type]...>

Values in a Collection MAY even be another array and even another Collection.

Type<Type<Type>>
Type<Type<Type[, Type]...>>
Type<Type<Type[|Type]...>>

Examples

<?php

$x = [new Name()];
/* @var $x Name[] */

$y = new Collection([new Name()]);
/* @var $y Collection<Name> */

$a = new Collection(); 
$a[] = new Model_User(); 
$a->resetChanges(); 
$a[0]->name = "George"; 
$a->echoChanges();
/* @var $a Collection<Model_User> */

Note: If you are expecting an IDE to do code assist then it's another question about if the IDE supports PHPDoc Generic-style collections notation.

Upvotes: 1

Related Questions