Skip to main content

PhysicalQuantity

PhysicalQuantity is the abstract base class shared by all quantity types. This page describes its public surface. For a method-by-method signature list, see the API reference.

Construction

public function __construct(float $originalValue, string|UnitOfMeasurement $unit)

The constructor stores the original value and unit, then computes the native value. The unit may be given as a string (a name or alias) or as a UnitOfMeasurement instance.

If the unit cannot be resolved — neither as a registered unit nor, where applicable, as an SI-prefixed base unit — the constructor throws InvalidArgumentException.

Properties

public readonly float $originalValue;
public readonly UnitOfMeasurement $originalUnit;
public readonly float $nativeValue;
public readonly UnitOfMeasurement $nativeUnit;

originalValue and originalUnit reflect the constructor arguments. nativeValue is the value converted to nativeUnit, the unit with conversion factor 1.0.

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

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

Immutability

All properties are readonly and every operation returns a new instance. The receiver is never mutated:

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

$a->nativeValue; // 5.0, unchanged
$b->nativeValue; // 8.0

Operations

The base class provides:

  • ConversiontoUnit(), toNativeUnit().
  • Arithmeticadd(), subtract(), multiply(), divide(), power().
  • ComparisoncompareTo(), greaterThan(), lessThan(), greaterThanOrEqualTo(), lessThanOrEqualTo(), equals().
  • Parsing and serializationparse() (static), jsonSerialize(), fromJson() (static).
  • String conversion__toString(), which returns "value unit" using the original value and unit.

These are documented in the guides.

Special-case hooks

Two protected methods are recognized by the constructor and conversion logic if a subclass defines them:

  • convertToNativeUnit(float $value, string $unitName): float — used during construction instead of multiplying by a conversion factor. Required for offset-based scales.
  • convertSIUnit(float $value, string $fromUnit, string $toUnit): float — provided by the HasSIUnits trait and used as the SI prefix fallback.

Temperature overrides convertToNativeUnit() and toUnit() to handle Celsius, Fahrenheit, and Rankine offsets. See Temperature.