Last active
September 18, 2017 12:44
-
-
Save chrisharrison/c5bea343f3cb6cf3dd065b177cb99da5 to your computer and use it in GitHub Desktop.
Interest rate calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Account | |
{ | |
private $capital; | |
private $rate; | |
public function __construct(float $capital, float $rate) | |
{ | |
$this->capital = $capital; | |
$this->rate = $rate; | |
} | |
public function transferIn(float $amount) : void | |
{ | |
if ($amount < 0) { | |
throw new Exception('Can\'t transfer negative amounts.'); | |
} | |
$this->capital += $amount; | |
return; | |
} | |
public function transferOut(Account $account, float $amount) : void | |
{ | |
if ($amount < 0) { | |
throw new Exception('Can\'t transfer negative amounts.'); | |
} | |
if ($amount > $this->capital) { | |
$amount = $this->capital; | |
} | |
$this->capital -= $amount; | |
$account->transferIn($amount); | |
return; | |
} | |
public function calculateAnnualInterest() : float | |
{ | |
return ($this->capital/100)*$this->rate; | |
} | |
public function calculateMonthlyInterest() : float | |
{ | |
return ($this->calculateAnnualInterest()/12); | |
} | |
} | |
$interest = 0; | |
$account1 = new Account(9000, 2); | |
$account2 = new Account(0, 2.25); | |
for ($i = 1; $i <= 12; $i++) { | |
$account1->transferOut($account2, 500); | |
$interest1 = $account1->calculateMonthlyInterest(); | |
$interest2 = $account2->calculateMonthlyInterest(); | |
$monthlyInterest = $interest1+$interest2; | |
$interest += $monthlyInterest; | |
echo 'Total for month ' . $i . ': ' . $interest1 . ' + ' . $interest2 . ' = ' . $monthlyInterest . PHP_EOL; | |
} | |
echo 'Total: ' . $interest; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment