Skip to content

Instantly share code, notes, and snippets.

@BrekiTomasson
Last active August 22, 2022 16:27
Show Gist options
  • Save BrekiTomasson/17cbd7bf5ec5bcaeb7bf2e30c9439ab8 to your computer and use it in GitHub Desktop.
Save BrekiTomasson/17cbd7bf5ec5bcaeb7bf2e30c9439ab8 to your computer and use it in GitHub Desktop.
A simple PHP trait that allows you to compare instances of one class to instances of any other class by implementing the getComparisonValue() method.
trait IsComparable
{
abstract public function getComparisonValue() : int|float|string;
/**
* @return int<-1, 1>
*/
public function compareTo($other) : int
{
if (! in_array(self::class, class_uses($other), true)) {
throw new RuntimeException('Compared class does not use IsComparable trait!');
}
return $this->getComparisonValue() <=> $other->getComparisonValue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment