phpdoc variable of class ArrayObject

你。 提交于 2019-12-12 05:16:40

问题


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:


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.



来源:https://stackoverflow.com/questions/39374921/phpdoc-variable-of-class-arrayobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!