Closed q2amarket closed 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.
@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.
@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.
@BenMorel Oh I see. Thanks for the details. I will retry this one..
I am not getting an idea of how can I use
->plus()
in foreach loop to get the total result?