The Money component was inspired by JSR 354 along with a few other ideas. It is mainly used for services and sites dealing with money.
Installation
composerrequiresonsofphp/money
Usage
Money
<?phpuseSonsOfPHP\Component\Money\Money;useSonsOfPHP\Component\Money\Currency;// Can use the Money Class like this$money =newMoney(100,newCurrency('USD'));$amount = $money->getAmount(); // AmountInterface$value = $amount->toString(); // `toInt` and `toFloat` are also supported// Or like this$money =Money::USD(100);
You can preform different operations to create new money.
<?phpuseSonsOfPHP\Component\Money\Money;$money =Money::USD(100);$newMoney1 = $money->add(Money::USD(100)); // Amount is now 200$newMoney2 = $money->subtract(Money::USD(100)); // Amount is now 0// The amount of the orginal Money does not change$amount = $money->getAmount(); // Amount is 100
You can multiple and divide too.
<?phpuseSonsOfPHP\Component\Money\Money;$money =Money::USD(100);$newMoney1 = $money->multiply(5); // value of Amount is now 500$newMoney2 = $money->divide(5); // value of Amount is now 20// The amount of the orginal Money does not change$amount = $money->getAmount(); // value of Amount is 100