class ArrayObject 的 phpdoc 变量

phpdoc variable of class ArrayObject

我有一个扩展 ArrayObject

的 class

class Collection extends ArrayObject

我知道我可以使用以下代码定义对象数组:

/* @var $userArray Model_User[] */

但是我如何将变量 $userArray 定义为包含 class Model_User 对象的 class Collection 的自定义数组?

不更改 class Collection 或其 phpdoc。 我想对不同的对象数组使用相同的 class Collection

这与PHPDoc type hinting for array of objects?不同,因为在该主题中讨论与php中的公共数组有关,php被定义为 /* @var $userArray Model_User[] */ 同时我的问题与自定义构建数组有关,如果 php 执行我上面的方法将不会键入自定义构建数组的提示方法 class,就像这样 $userArray->echoChanges() 因为它会认为它是一个普通数组,而不是 class 集合的数组。是的 $userArray 也充当数组,因此它应该键入提示数组内容 $userArray[3]->name.

PSR-5: PHPDoc 提出了一种泛型风格的表示法。

语法

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

集合中的值甚至可以是另一个数组甚至另一个集合。

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

例子

<?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> */

注意:如果您希望 IDE 执行代码辅助,那么关于 IDE 是否支持 PHPDoc 通用样式集合符号是另一个问题。