RE: [PHP-DEV] idea: implement a Comparable interface

From: Date: Wed, 08 May 2013 06:34:02 +0000
Subject: RE: [PHP-DEV] idea: implement a Comparable interface
References: 1 2  Groups: php.internals 
Request: Send a blank email to internals+get-67370@lists.php.net to get a copy of this message
> On Tue, May 7, 2013 at 6:17 PM, Thomas Anderson <zelnaga@gmail.com> wrote: > > > It'd be nice if, when doing $objA > $objB, that that'd invoke > > $objA->__compareTo($objB) or something, much like Java's Comparable > > interface. > > > > Do you have examples of what this would be useful for? The two things that > come to mind are DateTime (which can do this anyway as it's an internal > class) and classes for bignums or something like that (which are probably > also better implemented internally). So I'm not sure how much use there is > for this. > > Nikita I would like to see this feature in PHP! I often thought it would be very helpful. In days of PHP 5.2 I wrote a Date-Class similar to DateTime but with another API which should be the same as in C#. Comparing dates with `$date->compareTo($date2) > 0` is always hard to read and error-prone. Another example: You have one database entity and a collection and you want to check if it is in the collection. $dbEntity = ...; $dbCollection = ...; foreach ($dbCollection as $tmpEntity) { if ($dbEntity->getId() == $tmpEntity->getId()) { // ... } } Instead you could write `$dbEntity == $tmpEntity`. I think this is easier to read. Of course you can say "just syntetic sugar", but better readability of code helps developers a lot! Best regards Christian

« previous php.internals (#67370) next »