Generics proposal
| From: | Nikita | Date: | Sat, 20 Oct 2012 20:59:01 +0000 |
| Subject: | Generics proposal | ||
| Groups: | php.internals | ||
| Request: | Send a blank email to internals+get-63573@lists.php.net to get a copy of this message | ||
Hello, list. I want to propose generics. For those, who don't know what it is, here's
example: say we have a Comment class, that has a method getBody. Also we have Collection class, that
implements Traversable. Now, if I want to validate all insertions into collection of comments, I
would need to create CommentCollection class, extend it from Collection, and override all the
methods that are dealing with adding new elements to collection. Moreover, I can't have any
hints from my IDE about type of collection's elements, so if I'll have code like this:
foreach ($commentCollection as $comment) {
$comment->getBody();
}
There will be no way for IDE to know, of what type that object will be.
But there's how I could solve my problem with generics:
class Collection<T> implements Traversable
{
...
public function add(T $element){}
}
$collection = new Collection<Comment>();
$collection->add(new Comment());
$collection->add("that will be error");
Actually, that's, again, all about type hinting. If we went so far with scalar type hinting,
then generics would also be a good addition.
So, what you think?