Searching...
Sunday 30 June 2013

Functions in php – Part 4


Recursive Functions

Recursive functions, or functions that call themselves, offer considerable practical value to the programmer and are used to divide an otherwise complex problem into a simple case, reiterating that case until the problem is resolved. Practically every introductory recursion example involves factorial computation. Let’s do something a tad more practical and create a loan payment calculator. Specifically, the following example uses recursion to create a payment schedule, telling you the principal and interest amounts required of each payment installment to repay the loan. The recursive function, amortizationTable(), is introduced in script 1. It takes as input four arguments: $pNum, which identifies the payment number; $periodicPayment, which carries the total monthly payment; $balance, which indicates the remaining loan balance; and $monthlyInterest, which determines the monthly interest percentage rate. These items are designated or determined in the script 2.

Script 1. The Payment Calculator Function, amortizationTable()
function amortizationTable($pNum, $periodicPayment, $balance, $monthlyInterest)
{
// Calculate payment interest
$paymentInterest = round($balance * $monthlyInterest, 2);
// Calculate payment principal
$paymentPrincipal = round($periodicPayment - $paymentInterest, 2);
// Deduct principal from remaining balance
$newBalance = round($balance - $paymentPrincipal, 2);
// If new balance < monthly payment, set to zero
if ($newBalance < $paymentPrincipal) {
$newBalance = 0;
}
printf("<tr><td>%d</td>", $pNum);
printf("<td>$%s</td>", number_format($newBalance, 2));
printf("<td>$%s</td>", number_format($periodicPayment, 2));
printf("<td>$%s</td>", number_format($paymentPrincipal, 2));
printf("<td>$%s</td></tr>", number_format($paymentInterest, 2));
# If balance not yet zero, recursively call amortizationTable()
if ($newBalance > 0) {
$pNum++;
amortizationTable($pNum, $periodicPayment,
$newBalance, $monthlyInterest);
} else {
return 0;
}
}

After setting pertinent variables and performing a few preliminary calculations, script 2 invokes the amortizationTable() function. Because this function calls itself recursively, all amortization table calculations will be performed internal to this function; once complete, control is returned to the caller.

Script 2. A Payment Schedule Calculator Using Recursion
<?php
// Loan balance
$balance = 10000.00;
// Loan interest rate
$interestRate = .0575;
// Monthly interest rate
$monthlyInterest = $interestRate / 12;
// Term length of the loan, in years.
$termLength = 5;
// Number of payments per year.
$paymentsPerYear = 12;
// Payment iteration
$paymentNumber = 1;
// Determine total number payments
$totalPayments = $termLength * $paymentsPerYear;
// Determine interest component of periodic payment
$intCalc = 1 + $interestRate / $paymentsPerYear;
// Determine periodic payment
$periodicPayment = $balance * pow($intCalc,$totalPayments) * ($intCalc - 1) / (pow($intCalc,$totalPayments) - 1);
// Round periodic payment to two decimals
$periodicPayment = round($periodicPayment,2);
// Create table
echo "<table width='50%' align='center' border='1'>";
echo "<tr>
<th>Payment Number</th><th>Balance</th>
<th>Payment</th><th>Principal</th><th>Interest</th>
</tr>";
// Call recursive function
amortizationTable($paymentNumber, $periodicPayment, $balance, $monthlyInterest);
// Close table
echo "</table>";
?>

Figure below shows sample output, based on monthly payments made on a five-year fixed loan of $10,000.00 at 5.75 percent interest. For reasons of space conservation, just the first 12 payment iterations are listed.
recursivevfunctions_thumb[9]

Function Libraries

Personally I feel this is the most important part of functions. Great programmers are lazy, and lazy programmers think in terms of reusability. Functions offer a great way to reuse code and are often collectively assembled into libraries and subsequently repeatedly reused within similar applications. PHP libraries are created via the simple aggregation of function definitions in a single file, like this:

<?php
function localTax($grossIncome, $taxRate) {
// function body here
}
function stateTax($grossIncome, $taxRate, $age) {
// function body here
}
function medicare($grossIncome, $medicareRate) {
// function body here
}
?>

Save this library, preferably using a naming convention that will clearly denote its purpose, such as taxes.library.php. Do not, however, save this file within the server document root using an extension that would cause the web server to pass the file contents unparsed. Doing so opens up the possibility for a user to call the file from the browser and review the code, which could contain sensitive data. You can insert this file into scripts using include(), include_once(), require(), or require_once(). (Alternatively, you could use PHP’s auto_prepend configuration directive to automate the task of file insertion for you.) For example, assuming that you titled this library taxation.library.php, you could include it into a script like this:

<?php
require_once("taxation.library.php");
...
?>

Once included, any of the three functions found in this library can be invoked (invoking functions) as needed.


0 comments:

Post a Comment

 
Back to top!