Skip to main content

UnitOfMeasurement

UnitOfMeasurement represents a single unit within a quantity type. Each instance holds a name, a conversion factor relative to the native unit, and a list of aliases.

Construction

public function __construct(string $name, float $conversionFactor)

The name passed to the constructor is also registered as the first alias. The conversion factor expresses how many native units one of this unit equals.

use Renfordt\UnitLib\UnitOfMeasurement;

$foot = new UnitOfMeasurement('ft', 0.3048); // 1 ft = 0.3048 m

The native unit of a quantity always has a conversion factor of 1.0, because it is the unit all others are measured against.

Aliases

A unit can carry several names. Aliases let users supply common spellings and abbreviations:

$meter = new UnitOfMeasurement('m', 1);
$meter->addAlias('meter');
$meter->addAlias('metre');
$meter->addAlias('meters');

isAlias() checks whether a given string matches the unit's name or any of its aliases:

$meter->isAlias('metre'); // true
$meter->isAlias('ft'); // false

Property access

conversionFactor and aliases are exposed through PHP 8.4 property hooks as read-only virtual properties. Access them as properties, not method calls:

$foot->conversionFactor; // 0.3048
$foot->aliases; // ['ft', ...]
$foot->name; // "ft"

Where units are defined

Units are registered inside each quantity's initialise() method using addUnit(). The first unit added becomes the native unit. See Adding new quantities for how to define units for a new quantity type.