How can I make my own custom class be sortable using sort() for example?
I\'ve been scanning the web to find any method of making a class Comparable like in Java but wi
__toString()
works for me:
class Genre
{
private $genre;
private $count;
public function __construct( $genre, $count = 0 )
{
$this->genre = $genre;
$this->count = $count;
}
public function __toString()
{
return $this->count . ' ' . $this->genre;
}
}
$collection = array(
new Genre( 'alternative', 3 ),
new Genre( 'jazz', 2 ),
new Genre( 'hiphop', 1 ),
new Genre( 'heavy metal', 1 )
);
natsort( $collection );
foreach( $collection as $genre )
{
echo $genre . "\n";
}
Produces:
1 heavy metal
1 hiphop
2 jazz
3 alternative