On Sat, Oct 20, 2012 at 10:59 PM, Nikita <inefe...@gmail.com> 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?
Hah, I had the use case often, and every OO programmer has met this use case several time I think : Here is an example with SplObjectStorage (which is a good starting point structure for that) : <?php class MyClass extends SPlObjectStorage { public function attach(MyType $o, $data = null) { /* throws an E_STRICT we all know about */ return parent::attach($o, $data); } } Solution : <?php class MyClass extends SPlObjectStorage { public function attach($o, $data = null) { if (!$o instanceof MyType) { /* That is both ugly and boring to write */ throw new \RuntimeException(); } return parent::attach($o, $data); } } So, I'm +1 with the idea, but -1 with the proposed syntax. I'm +1 with Lars, as this can be done with a "TypeAsString", this is as well ugly, and I think we need PHP to provide a way to do that : <?php class Foo { public function __construct($type) { $this->type = $type; } public function add($o) { if (!$o instanceof $this->type) { throw new \RunTimeException("type {$this->type} expected"); } /* do something with $o*/ } } class Bar { } class Baz { } $f = new Foo('bar'); $f->add(new Bar); /* OK */ $f->add(new Baz); /* KO */ $f->add(array()); /* KO */ ?> IMO : this is something the language should take care of, not the developper, but that's my opinion :) -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php