Skip to main content

Creating and converting quantities

Creating a quantity

Instantiate a quantity class with a value and a unit. The unit may be a canonical name or any registered alias:

use Renfordt\UnitLib\Length;

$a = new Length(100, 'm');
$b = new Length(5.5, 'km');
$c = new Length(12, 'ft');

// Aliases
$d = new Length(1, 'meter');
$e = new Length(1, 'metre'); // British spelling
$f = new Length(10, 'inches');

If the unit is not recognized, the constructor throws InvalidArgumentException.

Converting to another unit

toUnit() returns the value expressed in the requested unit as a float:

$length = new Length(1500, 'm');

$length->toUnit('km'); // 1.5
$length->toUnit('mi'); // 0.932057...
$length->toUnit('ft'); // 4921.259...

toUnit() accepts either a unit name/alias or a UnitOfMeasurement instance. For quantities with SI support, prefixed units that are not explicitly registered are also accepted:

$length->toUnit('cm'); // 150000
$length->toUnit('μm'); // 1500000000

Converting to the native unit

toNativeUnit() returns a new quantity instance expressed in the native unit:

$length = new Length(100, 'cm');
$native = $length->toNativeUnit();

$native->originalValue; // 1.0
$native->originalUnit->name; // "m"

This differs from toUnit(), which returns a plain float. Use toNativeUnit() when you need a quantity object rather than a number.

Reading original and native values

Each instance retains both the value as supplied and the normalized value:

$length = new Length(100, 'cm');

$length->originalValue; // 100.0
$length->originalUnit->name; // "cm"
$length->nativeValue; // 1.0
$length->nativeUnit->name; // "m"

String representation

Quantities implement Stringable. Casting to a string yields the original value and unit:

echo new Mass(75, 'kg'); // "75 kg"
echo new Length(5280, 'ft'); // "5280 ft"