User Defined Functions

 

Introduction.  User defined functions are an important construct when programming.  They can be advantageous for a number of reasons.
  • debugging code segments
  • repeat use of code
  • repeat use of functionalities

Again, there are many other reasons for doing these sorts of things.

In general the syntax for developing functions is contained in the following table.  Again it looks very much like the syntax for JavaScript.

 

function function_name( )
{

//  function code

}

 

If you want the function to take some arguments from elsewhere the syntax changes slightly.

 

function function_name($arg_1, $arg_2, ..., $arg_n)
{

//  function code

}

 

If you want it to return something then you need to use that keyword within the function.

We will rework an earlier program where we calculated total cost based on unit price, quantity and taxes.  You should call the form page calculate_cost.html.

 

<html>
<head>
<title>Number Form</title>
</head>

<body bgcolor = "660000" text="cccccc">
<form action="calculate_cost.php" method=post>
<center><H2>Please enter the following information</H2></center>
<table align = center>
<tr>
<td><font size = 4 color=cccccc>Quantity:</font>
</td>
<td><input type=text name="txtQuantity" size=4>
</td>
</tr>
<tr>
<td><font size = 4 color=cccccc>Price:</font>
</td>
<td><input type=text name="txtPrice" size=4>
</td>
</tr>
<tr>
<td><font size = 4 color=cccccc>Tax Rate:</font>
</td>
<td><input type=text name="txtTaxRate" size=5>
</td>
</tr>
<tr>
<td colspan = 2 align = center><input type = submit name="submit" value="submit">
</td>
</tr>
</table>
</form>
</body>
</html>

 

Here we make use of a function that receives three arguments and returns one result using the return keyword.  I have also made certain to give different names to the variables local to the function.

You should call the processing script calculate_cost.php

 

<?php
// obtaining the information from the form and displaying it
function calculateCost($local_tax, $local_Quantity, $local_price)
{
$local_tax = $local_tax + 1.0;
$local_total = $local_Quantity * $local_price;
$local_total = $local_total * $local_tax;
return $local_total;
}
?>
<html>
<head>
<title>Echoing and Computing with the Inputted Information</title>
</head>

<body>
<?php
// obtaining the information from the form and displaying it
print "The order quantity is <b>$txtQuantity</b><BR>\n";
print "The price per item is <b>$txtPrice </b><BR>\n";
print "The tax rate is <b>$txtTaxRate </b><BR>\n";
$total_cost = calculateCost($txtTaxRate, $txtQuantity, $txtPrice);
print "<BR><BR>Your total cost including tax is <b>\$";
printf("%01.2f",$total_cost);
print "</b><BR>\n";
?>
</body>
</html>

 

Ultimately, the final result shouldn't seem any different to the end user.  But the code development has its advantages, particularly as programs get more involved.