# RFC: SPL Comparator interface

- Thread: https://externals.io/message/40881
- Original archive: https://news-web.php.net/php.internals/40881
- Started by Jeremy on 2008-10-07T22:50:23+00:00
- Messages: 2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #40881 — Jeremy — 2008-10-07T22:50:23+00:00

URL: https://externals.io/message/40881#40881

Something that would be extremely useful is a comparator interface in 
SPL, which could be used to easily implement sorting for objects.

Example:

class Foo implements Comparator
{
	// is numeric for this example
	public $bar;

	//implements compare method from Comparator interface
	public function compare($that)
	{
		//simple example; will return < 1 if this is less
		//than that; zero if they're equal; > 1 if this is
		//greater than that
		return $this->bar - $that->bar;
	}
}


Then, if I had an array of Foo objects, I could just call some kind of 
spl_sort function on the array which would use my comparator to sort them.

I realize this can be kludged with `usort()`, but I think there should be 
a better, OOP-ier way to do it.

I also realize that a similar effect could be achieved by defining an 
SPL PriorityQueue-ish collection rather than an array, but I think there 
ought to be a better way.  Java has a Comparator interface which works 
in much the same way, if that helps my case at all.

Jeremy

---

## #40883 — Marcus Boerger — 2008-10-08T22:47:08+00:00

URL: https://externals.io/message/40881#40883 · In reply to: #40881

Hello Jeremy,

Wednesday, October 8, 2008, 12:50:23 AM, you wrote:

> Something that would be extremely useful is a comparator interface in 
> SPL, which could be used to easily implement sorting for objects.

> Example:

> class Foo implements Comparator
> {
>         // is numeric for this example
>         public $bar;

>         //implements compare method from Comparator interface
>         public function compare($that)
>         {
>                 //simple example; will return < 1 if this is less
>                 //than that; zero if they're equal; > 1 if this is
>                 //greater than that
>                 return $this->bar - $that->bar;
>         }
> }


> Then, if I had an array of Foo objects, I could just call some kind of 
> spl_sort function on the array which would use my comparator to sort them.

> I realize this can be kludged with `usort()`, but I think there should be 
> a better, OOP-ier way to do it.

And for that exact reason we are adding closures in PHP 5.3.

Best regards,
 Marcus
