#!/usr/bin/env php 1.0, Unit::Kilometre => 1000.0, Unit::Foot => 0.3048, Unit::Mile => 1609.344, }; } } function convert(float $value, Unit $from, Unit $to): float { return $value * $from->inMetres() / $to->inMetres(); } // 5. $argv holds the arguments; $argv[0] is the script name. [$script, $value, $from, $to] = array_pad($argv, 4, null); $units = implode(', ', array_map(fn (Unit $u) => $u->value, Unit::cases())); if ($value === null || !is_numeric($value) || $from === null || $to === null) { // 6. Errors go to STDERR; the exit status tells the shell it failed. fwrite(STDERR, "Usage: php {$script} units: {$units}\n"); fwrite(STDERR, "Example: php {$script} 5 km mi\n"); exit(2); } // 7. tryFrom() returns null instead of throwing for an unknown unit. $fromUnit = Unit::tryFrom($from); $toUnit = Unit::tryFrom($to); if ($fromUnit === null || $toUnit === null) { fwrite(STDERR, "Unknown unit. Use one of: {$units}\n"); exit(2); } $result = convert((float) $value, $fromUnit, $toUnit); printf("%s %s = %s %s\n", $value, $fromUnit->value, round($result, 4), $toUnit->value);