Comparable
Reference
Definition
Namespace: Quant\Core\Contract
Comparable implements a total order for objects.
interface Comparable
Example
#[Getter]
class Money implements Comparable {
use AccessorTrait;
public function __construct(
private int $amount,
private int $cents
) {
}
public function compareTo(Comparable $b): array
{
if (!($b instanceof Money)) {
return false;
}
$aAmount = $this->getAmount();
$bAmount = $b->getAmount();
$aCents = $this->getCents();
$bCents = $b->getCents();
$c = ($aAmount === $bAmount ? 0 : ($aAmount < $bAmount ? -1 : 1));
return $c !== 0 ? $c : ($aCents < $bCents ? -1 : ($aCents > $bCents ? 1 : 0));
}
}
Remarks
This interface implements a total order on T for objects of T, with T being a subtype of Comparable. It provides a method compareTo whose implementation must, for all , conform to
->->->
In this regard, compareTo is
- reflexive:
$a->compareTo($a) - antisymmetric:
$a->compareTo($b)$b->compareTo($a)$a->compareTo($b) - transitive:
$a->compareTo($b)$b->compareTo($c)$a->compareTo($c) - total:
$a->compareTo($b)$b->compareTo($a)
The order should be consistent with objects implementing Equatable: If $a->equals($b) $a->compareTo($b)
Methods
| Name | Description |
|---|---|
compareTo(Comparable $obj): int | Returns -1 if $this is considered to be less than $obj, 0 if it's equal and 1 if $this is considered to be greater than $obj |