1. Go to this page and download the library: Download jimbo2150/php-comparable library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
jimbo2150 / php-comparable example snippets
use Jimbo2150\PhpComparable\Trait\ComparableTrait;
// This class will compare the Person object's $age property.
class Person
{
use ComparableTrait;
public function __construct(private string $name, private int $age)
{
assert($age > 0);
}
public function getComparableValue(): mixed
{
return $this->age;
}
}
$john = new Person('John', 29);
$karen = new Person('Karen', 24);
$john->compareTo($karen); // False, compares by equals (==) by default
$karen->compareTo($john, Operator::from('<')); // True, comparing with less than
use Jimbo2150\PhpComparable\Trait\ComparableTrait;
class Score
{
use ComparableTrait;
public const MIN_REQUIRED_SCORE = 1;
public function __construct(private float $score)
{
}
public function compareDiff(object $other): bool|int
{
$operator = Operator::GREATER_THAN_OR_EQUAL;
$diffFunction = fn (
mixed $leftValue,
mixed $rightValue,
Operator $operator,
): bool|int => $operator->compare(
$leftValue - $rightValue,
self::MIN_REQUIRED_SCORE
);
return $this->customCompareTo(
$diffFunction,
$other,
$operator
);
}
public function getComparableValue(): mixed
{
return $this->score;
}
}
$score1 = new Score(2.4);
$score2 = new Score(0.7);
$score3 = new Score(0.2);
$score1->compareDiff($score2); // True, score is >= 1
$score2->compareDiff($score3); // False, score is less than 1
bash
$ composer
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.