brick / money

A money and currency library for PHP
MIT License
1.65k stars 102 forks source link

How can I plus in foreach loop? #21

Closed q2amarket closed 5 years ago

q2amarket commented 5 years ago

I am not getting an idea of how can I use ->plus() in foreach loop to get the total result?

BenMorel commented 5 years ago

Hi, as Money is immutable, plus() returns a new object, so this won't work:

foreach (...) {
    $money->plus($amount);
}

As the original money will keep its value. Instead, do:

foreach (...) {
    $money = $money->plus($amount);
}

It's the same reasoning as if you worked with integers: $money + $amount would not change $money, while $money = $money + $amount would.

q2amarket commented 5 years ago

@BenMorel This is exactly I have done but instead of returning amount string it is returning whole object.

I would request you to test it at your side if not yet.

BenMorel commented 5 years ago

@q2amarket Yes, you will always get a Money object in return. You can cast it to a string and get something like:

echo (string) $money; // USD 5.00

Or you can get the amount only, which is an object too (a BigDecimal), also castable to string:

echo (string) $money->getAmount(); // 5.00

Or get the currency only, which is also an object (a Currency), also castable to string:

echo (string) $money->getCurrency(); // USD

I'm explicitly casting to (string) here, altough it's implicit when using echo, and as such not necessary in this case.

q2amarket commented 5 years ago

@BenMorel Oh I see. Thanks for the details. I will retry this one..