Psalm
Get started
Documentation
Plugins
Articles
GitHub
<?php /** @psalm-immutable */ abstract class MoneyAmount { public float $value; public function __construct(float $value) { $this->value = $value; } /** @psalm-pure */ abstract public static function getSymbol() : string; /** * @param static $amount * @return static */ public function add(self $amount) : self { return new static($amount->value + $this->value); } public function getFormatted() : string { return static::getSymbol() . number_format($this->value, 2); } } class GbpAmount extends MoneyAmount { public static function getSymbol() : string { return '£'; } } /** @psalm-immutable */ class UsdAmount extends MoneyAmount { public static function getSymbol() : string { return '$'; } public function convertToGbp(float $exchange_rate) : GbpAmount { return new GbpAmount($this->value * $exchange_rate); } } /** @psalm-pure */ function addSalesTaxAndConvertToGbp( UsdAmount $usd, float $exchange_rate ) : GbpAmount { return $usd ->add(new UsdAmount($usd->value * 0.08)) ->convertToGbp($exchange_rate); } $usd_amount = new UsdAmount(5.0); echo addSalesTaxAndConvertToGbp($usd_amount, 1.20)->getFormatted();
Snippet created on September 10 2019 at 04:35 UTC
Settings
Get link