RE: [PHP-DEV] idea: implement a Comparable interface
> On Tue, May 7, 2013 at 6:17 PM, Thomas Anderson <[email protected]> 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
Thread (17 messages)