Skip to content

03. Arithmetic

Jordan LeDoux edited this page Jan 16, 2017 · 15 revisions

Working With NumberInterface

Arithmetic can be performed on any class that implements the NumberInterface, and the rules for using arithmetic methods are consistent and straight-forward: you can put any value that is valid for an ImmutableNumber constructor in, or you can put in any instance of an object that implements NumberInterface itself.

Available Methods

The following arithmetic methods are available.

add(int|float|numeric|NumberInterface $num): self

This adds the argument to the Value using the ArithmeticProvider (which uses the BCMath library internally) and returns the newly calculated Value.

When an object that implements DecimalInterface and another that implements FractionInterface are added together, the one that is provided as an argument is coerced into the type of original object. For example:

<?php

use Samsara\Fermat\Values\ImmutableNumber;
use Samsara\Fermat\Values\ImmutableFraction;

$five = new ImmutableNumber(5);
$oneQuarter = new ImmutableFraction(1, 4);

echo $five->add($oneQuarter); // Prints: "5.25" 
// The asDecimal() method is called on $oneQuarter

echo $oneQuarter->add($five); // Prints: "21/4" 
// Calls getValue() on $five and instantiates a new ImmutableFraction

subtract(int|float|numeric|NumberInterface $num): self

This subtracts the argument from the Value using the ArithmeticProvider (which uses the BCMath library internally) and returns the newly calculated Value.

When an object that implements DecimalInterface and another that implements FractionInterface are subtracted, the one that is provided as an argument is coerced into the type of original object. For example:

<?php

use Samsara\Fermat\Values\ImmutableNumber;
use Samsara\Fermat\Values\ImmutableFraction;

$five = new ImmutableNumber(5);
$oneQuarter = new ImmutableFraction(1, 4);

echo $five->subtract($oneQuarter); // Prints: "4.75" 
// The asDecimal() method is called on $oneQuarter

echo $oneQuarter->subtract($five); // Prints: "-19/4" 
// Calls getValue() on $five and instantiates a new ImmutableFraction

multiply(int|float|numeric|NumberInterface $num): self

This multiplies the argument from the Value using the ArithmeticProvider (which uses the BCMath library internally) and returns the newly calculated Value.

When an object that implements DecimalInterface and another that implements FractionInterface are miltiplied, the one that is provided as an argument is coerced into the type of original object. For example:

<?php

use Samsara\Fermat\Values\ImmutableNumber;
use Samsara\Fermat\Values\ImmutableFraction;

$five = new ImmutableNumber(5);
$oneQuarter = new ImmutableFraction(1, 4);

echo $five->multiply($oneQuarter); // Prints: "1.25" 
// The asDecimal() method is called on $oneQuarter

echo $oneQuarter->multiply($five); // Prints: "5/4" 
// Calls getValue() on $five and instantiates a new ImmutableFraction