Skip to content

Instantly share code, notes, and snippets.

@jasny
Last active Jul 6, 2021
Embed
What would you like to do?
Idea for Unit PHP extension
<?php
$distance = new Meter(3);
$cm = $distance->in(Centimeter::class);
ecoh $distance; // 3m
echo $cm; // 300cm
$distance == Decimeter(30); // True
$distance === Decimeter(30); // False
$distance->in(Volts::class); // UnitConversionException
$distance->canConvertTo(Volts::class); // false
// Use consts, rather then methods for static analysis
class Meter extends Unit
{
public const UNIT = "m";
public const CONVERT = [
Milimeter::class => 0.001,
Centimeter::class => 0.01,
Decimeter::class => 0.1,
Decameter::class => 10,
Hectometer::class => 100,
Kilometer::class => 1000,
];
}
// Disadvantage, this needs to be repeated for every distance class. Maybe use a base class
abstract class Distance extends Unit
{
public const BASE = Meter::class;
}
class Centimeter extends Distance
{
public const UNIT = "cm";
public const RATIO = 0.01;
}
// Operators
$further = $distance + (new Decimeter(6)); // Meter(3.6)
$further2 = (new Decimeter(6)) + $distance; // Decimeter(36)
$closer = $distance - (new Decimeter(6)); // Meter(2.4)
$ratio = $distance / (new Decimeter(6)); // 5
// How can we do something like?
$surface = (new Meter(10)) * (new Meter(5)); // SquareMeter(50);
// Combined units ?
$m34 = new Meters(3.4);
$d34 = $d2->in(Kilometer::class, Meter::class, Millimeter::class); // Unit\Combined([Meter(3), Millimeter(400)])
echo $m34; // 3.14m
echo $d34; // 3m 400mm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment