Skip to main content

UnitLib

UnitLib is a PHP 8.4+ library for representing physical quantities and converting between units of measurement. It covers SI metric units, imperial and US customary units, and a number of domain-specific units (nautical, CGS, battery capacity, and others).

The package is published as renfordt/unit-lib.

What it does

  • Represents a measured value together with its unit as an immutable object.
  • Converts a value to any other registered unit of the same quantity.
  • Resolves SI metric prefixes (k, m, μ, M, G, …) automatically for quantities that declare an SI base unit.
  • Performs arithmetic between quantities. Addition and subtraction return the same quantity type; multiplication, division, and exponentiation return derived quantity types (for example Length × Length produces Area).
  • Compares quantities of the same type with automatic unit normalization.
  • Parses strings such as "5.5 meters" into quantity objects.
  • Serializes quantities to and from JSON.

Design summary

Every quantity type extends an abstract base class, PhysicalQuantity. The base class stores both the value as supplied (originalValue / originalUnit) and the value normalized to the type's native unit (nativeValue / nativeUnit). Conversions and comparisons operate on the native value, so the unit a value was created in does not affect the result.

Units are described by UnitOfMeasurement objects, each holding a conversion factor relative to the native unit and an optional set of aliases. SI prefix handling is provided by the HasSIUnits trait, which a quantity includes when metric prefixes apply.

See Architecture for a fuller description.

Requirements

  • PHP 8.4 or higher. The library uses property hooks, array_find(), and the #[\Override] attribute, all of which require 8.4.

Next steps