Re: Generics proposal

From: Date: Sat, 20 Oct 2012 21:02:00 +0000
Subject: Re: Generics proposal
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-63574@lists.php.net to get a copy of this message
On 10/20/2012 01:59 PM, Nikita wrote: > 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? Personally I would hate to see this anywhere near PHP. -Rasmus

« previous php.internals (#63574) next »