Skip to main content

Arithmetic operations

add() and subtract() combine two quantities of the same type. Multiplication, division, and exponentiation produce derived quantity types and are covered separately in Derived units.

Addition and subtraction

Both operands are normalized to the native unit before the operation, so they may be in different units:

use Renfordt\UnitLib\Length;

$a = new Length(1, 'km');
$b = new Length(500, 'm');

$sum = $a->add($b);
$sum->toUnit('km'); // 1.5
$sum->toUnit('m'); // 1500

$diff = $a->subtract($b);
$diff->toUnit('m'); // 500

Result is in the native unit

add() and subtract() always return a new instance expressed in the native unit, not in the unit of either operand. Use toUnit() to convert the result to whatever unit you need:

$result = (new Length(2, 'ft'))->add(new Length(3, 'ft'));

$result->originalUnit->name; // "m", not "ft"
$result->toUnit('ft'); // 5.0

Type compatibility

add() and subtract() accept any PhysicalQuantity. They operate on native values and do not check that the two operands are the same quantity type, so it is the caller's responsibility to combine compatible quantities. For type-checked operations, use the comparison methods, which reject mismatched types (see Comparison).

Immutability

The operands are never modified. Each operation returns a new instance:

$a = new Length(5, 'm');
$a->add(new Length(3, 'm'));

$a->nativeValue; // still 5.0