In an effort to utilize OOP in PHP, I was looking for a way to define functions within objects to use for sorting. in Java this is simple, as the compareTo()
is automatically called by sorted arrays and such. I looked around PHP.net and couldn't find anything similar in PHP. I have resorted to what seems like a hack to me, so I'm wondering if anyone can lend some insight on an easier way.
CURRENT CODE:
class SomeObject {
private $someField;
function getSomeField() { return $this->someField; }
function compareTo($other) {
return $this->someField - $other->getSomeField();
}
}
//in funcs.php
function objSort($a, $b) {
return $a->compareTo($b);
}
//To sort an array
usort($array, objSort);
Is there an easier/more sleek way of doing this in PHP?