Parsing strings
PhysicalQuantity::parse() turns a string such as "5.5 meters" into a quantity
object.
public static function parse(string $input, ?string $expectedClass = null): PhysicalQuantity
Auto-detection
Without a second argument, parse() extracts the number and unit, then tries each known
quantity type in turn and returns the first that accepts the unit:
use Renfordt\UnitLib\PhysicalQuantity;
$length = PhysicalQuantity::parse('5.5 meters');
$mass = PhysicalQuantity::parse('100 kg');
$temp = PhysicalQuantity::parse('-40 °C');
Because detection depends on which type first recognizes the unit, a unit that is shared across types resolves to the first matching type in the library's internal order. When the type is known in advance, pass it explicitly to avoid ambiguity.
Explicit type
Passing the target class skips detection and constructs that type directly:
use Renfordt\UnitLib\Length;
$distance = PhysicalQuantity::parse('100 km', Length::class);
Accepted formats
The input is a number followed by a unit. A space between them is optional, and the number may carry a sign or a decimal point:
PhysicalQuantity::parse('5.5 m'); // with space
PhysicalQuantity::parse('100km'); // without space
PhysicalQuantity::parse('-10 meters'); // negative
PhysicalQuantity::parse('+5 kg'); // explicit positive sign
Errors
parse() throws InvalidArgumentException when:
- the input does not match the
number unitshape, - no unit is present after the number, or
- the unit is not recognized by any quantity type (or by the explicit type, if given).