Re: [RFC:generics]
| From: | Rowan Collins | Date: | Wed, 20 Apr 2016 15:25:08 +0000 |
| Subject: | Re: [RFC:generics] | ||
| References: | 1 2 3 4 5 6 7 8 9 10 11 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-92552@lists.php.net to get a copy of this message | ||
Larry Garfield wrote on 20/04/2016 16:12:
On 4/20/16 10:01 AM, Rowan Collins wrote:The is/extends/instanceof clause adds to the rule: "...they can be any same type, *as long as that type meets this constraint*" So using an unbounded generic, you could manually check: class FileProcessor<T> { public function __construct(T $t) { assert($t instanceof FileHandle); } } $f = new FileProcessor<ZipArchiveEntryHandle>($zip->getEntryHandle(1)); // "T" is substituted for "ZipArchiveEntryHandle" $f = new FileProcessor<int>(42); // assertion fails! A bounded generic, using "is" as the keyword as in the current RFC, performs the assertion for you: class FileProcessor<T is FileHandle> { public function __construct(T $t) { // no need for an assertion } } $f = new FileProcessor<int>(42); // throws a TypeError My suggestion was that the constraint is like an "instanceof" assertion, so we could use that keyword: class FileProcessor<T instanceof FileHandle> { public function __construct(T $t) { // no need for an assertion } } $f = new FileProcessor<int>(42); // throws a TypeError I hope that makes sense. Regards, -- Rowan Collins [IMSoP]guilhermeblanco@gmail.com wrote on 20/04/2016 03:54:I'm not an expert in generics by any means, but how is that different than just public function __construct(Boxable $t) {} I thought the point of generics was for cases like "these two variables must be the same type, but they can be any same type."1- Even though mentioned, I'd still use "extends" or "implements" instead of "is" (which would be a new pseudo-reserved keyword) to enforce data type consistency and prevent developers to potentially referring to one thing while consider another.Perhaps "instanceof" would make more sense here? "class FileProcessor<T extends FileHandle>" seems to exclude instantiating FileProcessor<FileHandle>, because "FileHandle extends FileHandle" doesn't make any sense. You could read "class Box<T instanceof Boxable>" as an assertion that the class passes the constraint, as in "public function __construct(T $t) { assert($t instanceof Boxable); }" Regards,