Skip to content

Instantly share code, notes, and snippets.

@mvriel
Created October 2, 2012 20:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mvriel/3823010 to your computer and use it in GitHub Desktop.
Save mvriel/3823010 to your computer and use it in GitHub Desktop.
Generic notation in PHPDoc vs. plain array notation
<?php
/**
* @template <T> The type of the individual elements
*/
class ArrayCollection implements IteratorAggregate
{
private $elements;
/**
* @param array<T> $elements
*/
public function __construct(array $elements)
{
$this->elements = $elements;
}
/**
* @return Iterator<T>
*/
public function getIterator()
{
return new ArrayIterator($this->elements);
}
}
// usage
/** @type ArrayCollection<Foo> $col */
$col = new ArrayCollection();
foreach ($col as $elem) {
// $elem is instance of Foo here
}
?>
<?php
class ArrayCollection implements IteratorAggregate
{
private $elements;
/**
* @param mixed[] $elements
*/
public function __construct(array $elements)
{
$this->elements = $elements;
}
/**
* @return ArrayIterator
*/
public function getIterator()
{
return new ArrayIterator($this->elements);
}
}
// usage
/** @type ArrayCollection|Foo[] $col */
$col = new ArrayCollection();
foreach ($col as $elem) {
// $elem is instance of Foo here
}
?>
@cmrafifar
Copy link

Coming from a Java perspective, I would love some kind of Generics support in PHP and/or PHPDOC. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment