About 5-6 years ago I had my “PHP should be more like Java” phase and experimented a lot with things like string objects and method overloading, which usually required hackish workarounds and most things did not turn out to be very practical in the long run.
But there is one package I still like very much, namely ComparatorTools, which got to be place 2 in the monthly PHPclasses.org innovation awards after all. It provides Comparable
and Comparator
interfaces and functions similar to the core array functions, that can work with these.
Interfaces
The interfaces resemble the corresponding Java interfaces, except that we do not have Generics in PHP, so it is cannot be guaranteed that compared objects have the same type. This has to be checked at runtime in the implementation, if needed. An exception type for these cases is provided:
interface Comparable { /** * @param object $object * @return numeric negative value if $this < $object, positive if $this > $object, 0 otherwise (if objects are considered equal) * @throws ComparatorException if objects are not comparable to each other */ public function compareTo($object); }
interface Comparator { /** * @param object $object1 * @param object $object2 * @return numeric Negative value if $object1 < $object2, positive if $object1 > $object2, 0 otherwise * @throws ComparatorException if objects are not comparable to each other */ public function compare($object1, $object2); }