Quick start
The examples below show the most common operations. Each quantity class lives in the
Renfordt\UnitLib namespace.
Create and convert
use Renfordt\UnitLib\Length;
$distance = new Length(100, 'km');
$distance->toUnit('mi'); // 62.137119 (miles)
$distance->toUnit('m'); // 100000 (meters)
The constructor takes a numeric value and a unit name or alias. toUnit() returns the
value expressed in the requested unit as a float.
SI prefixes
Quantities that declare an SI base unit accept metric prefixes without needing each prefixed unit to be registered explicitly:
$height = new Length(1.75, 'm');
$height->toUnit('cm'); // 175
$height->toUnit('mm'); // 1750
Arithmetic
Addition and subtraction accept any unit of the same quantity and return a new instance in the native unit:
$total = (new Length(5, 'km'))->add(new Length(500, 'm'));
$total->toUnit('km'); // 5.5
Derived units
Multiplication, division, and exponentiation produce derived quantity types:
use Renfordt\UnitLib\{Length, Time};
$area = (new Length(5, 'm'))->multiply(new Length(3, 'm'));
$area->toUnit('m²'); // 15 (an Area)
$velocity = (new Length(100, 'm'))->divide(new Time(10, 's'));
$velocity->toUnit('m/s'); // 10 (a Velocity)
Temperature
Temperature uses offset-based scales and is handled as a special case:
use Renfordt\UnitLib\Temperature;
$temp = new Temperature(0, '°C');
$temp->toUnit('°F'); // 32
$temp->toUnit('K'); // 273.15
Comparison
$a = new Length(1, 'km');
$b = new Length(500, 'm');
$a->greaterThan($b); // true
$a->equals(new Length(1000, 'm')); // true
Parsing
use Renfordt\UnitLib\PhysicalQuantity;
$length = PhysicalQuantity::parse('5.5 meters');
$mass = PhysicalQuantity::parse('100 kg');
Continue with the guides for detailed explanations of each operation.