0
votes

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.

1
not even close, my array can have its own functions, like $userArray->resetChanges() so it should type hint + its also acts as an array $userArray[4] ->name and it should type hint as well.YuraV
In other words what your asking is: where $x = [new Name()]; then /* @var $x Name[] */ so $y = new Collection([new Name()]); then /* @var $y ? */Gerard Roche
code will work like this: $a = new Collection(); $a[] = new Model_User(); $a->resetChanges(); $a[0]->name = "George"; $a->echoChanges(); and i dont know how to phpdoc $a, so its knew it has methods of class Collection and contains objects of class Model_User. just in case php.net/manual/ru/class.arrayobject.phpYuraV

1 Answers

1
votes

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.