Created
October 2, 2012 20:14
-
-
Save mvriel/3823010 to your computer and use it in GitHub Desktop.
Generic notation in PHPDoc vs. plain array notation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
} | |
?> |
I have been thinking quite a bit about this proposal in the past time and to be honest, it is starting to grow on me. Though I am not so sure about the @template
tag since that would only serve a purpose for a Collection object that only intends to be used with a specific set of values (that and I don't think the name @template
is intuitive).
Some concerns that I still have:
- How to deal with generics where the value may be of several types? Use the or operator (|) as has been done so far?
- We should also support multi-dimensional notations
I think we sould keep the or operator for working with several types. But what do you mean by "multi-dimensional notations"?
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
Could these ideas be successfully condensed into just this one syntax:
@type (class name or primitive type 'array')<(optional key type, ) (required member type) (description)