Home

Creating and Using Functions

Techniques of Creating and Using Functions

A Function in a Function

In PHP, a function can be created in the body of another function. Here are examples:

<?php
function gather()
{
    function display()
    {
        return "Welcome to the wonderful world of PHP!";
    }
    function calculate($number)
    {
        return $number * $number;
    }
}
?>

Before access the internal functions, you must first call the function container. Here is an example:

<?php
function gather()
{
    function display()
    {
        return "Welcome to the wonderful world of PHP!";
    }
    function calculate($number)
    {
        return $number * $number;
    }
}

gather();

$msg = display();
$calculation = calculate(24.50);

echo "Message: $msg<br>";

echo "Result: $calculation";
?>

This would produce:

A Function in a Function

Recursive Functions

A recursive function is a function that calls itself. Usually, the function performs an operation first, then calls itself to perform the operation again. Because this can be done over and over again, the function must specify when and how to stop. Here is an example:

<?php
function additionalOdd($a)
{
    if($a <= 1)
        return 1;
    else
        return $a + additionalOdd($a - 2);
}

$sum = additionalOdd(9);

echo "Sum of odd numbers from 1 to 9: $sum";
?>
</body>
</html>

This would produce:

Recursive Functions

Techniques of Passing Arguments

Passing an Argument by Value

When calling a function that takes one or more arguments, you must provide the necessary value(s) for the argument(s). This is because an argument is always required and the calling function must provide a valid value when calling such a function. This technique of providing a value for the argument is referred to as passing an argument by value.

Passing an Argument by Reference

Consider the following program:

<?php
function getDeposit($amount)
{
    $amount = 450;

     echo "In GetDeposit(), ";
     echo "Amount: \$$amount<br>";
}

$amt = 0;

echo "In Main(), ";
echo "Amount: \$$amt<br>";

getDeposit($amt);
        
echo "Back in Main(), ";
echo "Amount: \$$amt";
?>

This would produce:

Passing an Argument by Reference

Notice that the value of the argument is the same before and after calling the getDeposit() function. When you declare a variable, the PHP interpreter reserves an amount of space for that variable. If you need to use that variable somewhere, you can simply access it and use its value. There are two major issues related to a variable: its value and its location in the memory. The location of a variable in memory is referred to as its address.

If you supply the argument using its name, the compiler only makes a copy of the argument's value and gives it to the calling function. Although the calling function receives the argument's value and can use it in any way, it cannot (permanently) alter it. An alternative is to call a function to modify the value of an argument if you find it necessary. If you want the calling function to modify the value of a supplied argument and return the modified value, you can pass the argument using its reference.

To pass an argument as a reference, when defining the function, precede the argument's name with the & symbol. Here is an example:

function getDeposit(&$amount)
{
}

In the function, you can use or ignore the argument. When calling the function, simply use the argument as we have done so far. here is an example:

<?php
function getDeposit(&$amount)
{
    $amount = 450;

    echo "In GetDeposit(), ";
    echo "Amount: \$$amount<br>";
}

$amt = 0;

echo "In Main(), ";
echo "Amount: \$$amt<br>";

getDeposit($amt);
        
echo "Back in Main(), ";
echo "Amount: \$$amt";
?>

This would produce:

Passing an Argument by Reference

The true purpose of passing an argument by reference is to allow the function to change the value of the argument. To make this possible, in the function, make sure you change the value of the argument. Here is an example:

<?php
function getDeposit(&$amount)
{
    $amount = 1225;

     echo "In GetDeposit(), ";
     echo "Amount: \$$amount<br>";
}

$amt = 380;

echo "In Main(), ";
echo "Amount: \$$amt<br>";

getDeposit($amt);
        
echo "Back in Main(), ";
echo "Amount: \$$amt";
?>

This would produce:

Passing an Argument by Reference

You can pass 0, one, or more arguments as reference or pass all arguments as reference. The decision as to which argument(s) should be passed by value or by reference is based on whether or not you want the called function to modify the argument and permanently change its value.

When we studied the fact that a function can return a value, we saw that a function can return only one value because there is only one return keyword. Fortunately, the ability to pass many arguments by reference makes it possible for a function to return many values.

Optional Arguments: A Default Value for a Parameter

We have learned that if a function takes an argument, when you call that function, you must provide a value for the argument. There is an exception to this rule. If you have a function whose argument is usually given the same value, you can give a default value to that argument. To specify that an argument has a default value, in the parentheses of the function, after the name of the argument, assign the default value to it. Here is an example:

<?php
function calculateNetPrice($discountRate = 25)
{
    $origPrice = 125.55;

    return $origPrice - ($origPrice * $discountRate / 100);
}
?>

When calling the function, you can pass a value for the argument. If you want to use the default value, omit passing the argument. Here is an example:

<?php
function calculateNetPrice($discountRate = 25)
{
    $origPrice = 125.55;

    return $origPrice - ($origPrice * $discountRate / 100);
}

$finalPrice = calculateNetPrice();

echo "After applying the discount<br>";
echo "Final Price = $finalPrice";
?>

Notice that the parentheses of the function are empty, which means that the argument was not passed. This would produce:

Optional Argument: A Default Value for a Parameter

In the same way, you can create a function that takes many arguments and some or all of those arguments can have default values. If a function takes more than one argument, you can provide a default argument for each and select which one(s) would has (have) (a) default value(s). If you want all arguments to have default values, when defining the function, type each name followed by = and followed by the desired value. Here is an example:

<?php
function calculateNetPrice($tax = 5.75,
                           $discount = 25,
                           $origPrice = 245.55)
{
    $discountValue = $origPrice * $discount / 100;
    $taxValue      = $tax / 100;
    $netPrice      = $origPrice - $discountValue + $taxValue;

    echo "Original Price: $origPrice<br>";
    echo "Discount Rate: $discount%<br>";
    echo "Tax Amount: $tax<br>";

    return $netPrice;
}

$finalPrice = calculateNetPrice();

echo "After applying the discount<br>";
echo "Final Price = $finalPrice";
?>

This would produce:

Optional Argument: A Default Value for a Parameter

If a function takes more than one argument and you would like to provide default values for those parameters, the order of appearance of the arguments is very important. If a function takes two arguments, you can declare it with default values. We already know how to do that. If you want to provide a default value for only one of the parameters, the parameter that would have a default value must be the second. When calling such a function, if you supply only one argument, the interpreter would assign its value to the first parameter in the list and ignore assigning a value to the second:

<?php
function calculateNetPrice($taxRate, $discountRate = 25)
{
    $origPrice = 185.95;

    $discountValue = $origPrice * $discountRate / 100;
    $taxValue = $taxRate / 100;
    $netPrice = $origPrice - $discountValue + $taxValue;

    return $netPrice;
}

$taxRate = 5.50; // = 5.50%
$finalPrice = calculateNetPrice($taxRate);

echo "After applying a 25% discount and a 5.50% tax rate<br>";
echo "Final Price = $finalPrice";
?>

Here is an example of running the program:

Optional Argument: A Default Value for a Parameter

If you define the function and assign a default value to the first argument, if you provide only one argument when calling the function, you would receive an error.

If the function receives more than two arguments and you would like only some of those arguments to have default values, the arguments that have default values must be at the end of the list. Regardless of how many arguments would or would not have default values, start the list of arguments with those that would not use default values. When calling the function, you can provide a value for only the argument(s) that do(es) not have a default value.

Anonymous Functions

Introduction

An anonymous function is a function that is not primarily created before being used. The function is directly created where it action is needed. As a result, the anonymous function doesn't stand in its own position and it doesn't have a name. Such a function is also called a closure.

To create an anonymous function, use the usual function keyword without a name for the function. After the keyword, add the usual parentheses of a function. The function many or may not use parameters. After the parentheses, create the body of the function delimited by curly brackets. The formula to follow is:

function(parameter(s)){ body
}

An Anonymous Function With No Parameters

You can create an anonymous function that takes no parameter. In this case, you can leave its parentheses empty. Here is an example:

<?php
$show = function(){
        echo "Welcome to this wonderful world!<br>";
};
?>

In this example, we assigned an anonymous function to a variable. After doing this, you can use the variable as if it was a function; that is, you can use it as if you were calling its function. Here is an example:

<?php
$show = function(){
        echo "Welcome to this wonderful world!";
};

$show();
?>

This would produce:

Anonymous Functions

Just like any function, an anonymous function is usually created to perform a specific action or a group of related actions. Here is an example of one that is used to create or hold a form:

<?php
$create = function(){
    echo"<form name='frmBasicMath' method='post'>
         <p><b>Business Mathematics</b></p>
         <table border='4'>
        <tr>
          <td>Value:</td>
          <td><input name='txtValue' value='$value'></input>%</td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td><input name='Submit' type='submit' value='Convert' />
          </td>
        </tr>
        <tr>
          <td>Converted:</td>
          <td><input name='txtConverted' value='$converted'></input></td>
        </tr>
      </table>
    </div>
    </form>";
};

$create();
?>

Anonymous Functions With Parameters

an anonymous function can take a parameter. To specify it, in the parentheses of function, type the name of the parameter preceded by its $ symbol. In the body of the anonymous function, you can use or ignore the parameter. Here is an example:

<?php
$calculate = function($x)
{
    return $x / 100.00;
};
?>

To use the value of the anonymous function, you can use the variable followed by parentheses as done when calling a function. In the parentheses, provide the argument.many options. Here is an example:

<?php
$calculate = function($x){ return $x / 100.00; };

echo"<form name='frmBasicMath' method='post'>
         <p><b>Business Mathematics</b></p>
         <table border='4'>
        <tr>
          <td>Value:</td>";

$value = (float)htmlspecialchars($_POST['txtValue']);

echo "          <td><input name='txtValue' type='text' value='$value'></input>%</td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td><input name='Submit' type='submit' value='Convert' />
          </td>
        </tr>
        <tr>
          <td>Converted:</td>";

$result = $calculate($value);

echo "          <td><input name='txtConverted' type='text' value='$result'></input></td>
        </tr>
      </table>
    </div>
    </form>";
?>

Here is an example of using the webpage:

Anonymous Functions

Anonymous Functions

One of the most common reasons to use an anonymous function is to create a function that is needed only once. Other than that, an anonymous function can be as complex as you want, not just a simple one-line statement. It can include its own local variables and it can have internal expressions such as conditional statements. Here is an example:

Author Note

Piecework is a system by which an employee (or contractor) is paid based on a number of units or items. Examples are the number of pineapples an employee has collected in a farm, the number chips an employee has assembled, the number shirts sewn, etc.

Companies use two primary ways to pay their piecework employees. In one case, an employee can be paid straight on the number of units. In another case, there is a rate on the first number of items such as 100, then there is a second rate for the second fraction such as units between 101 and 200, and finally there is a last rate such as for the number of units over 200.

In the following example, a microchip company is paying employees who assemble the chips:

Units Price Each
Between 1 and 100 units 2.25
From 101 to 250 2.45
More Than 250 2.68
<?php
echo"<form name='frmMicrochipCompany' method='post'>
         <p><b>Microchip Company</b></p>
         <table border='4'>
        <tr>
          <td>Number of Units:</td>";

$units = (float)htmlspecialchars($_POST['txtUnits']);

echo "          <td><input name='txtUnits' type='text' value='$units'></input></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td><input name='Submit' type='submit' value='Calculate' />
          </td>
        </tr>
        <tr>
          <td>Gross Salary:</td>";

$grossSalary = function($units){
    if($units <= 100.00)
        return $units * 2.25;
    elseif($units <= 250.00)
    {
        $first100 = 100.00 * 2.45;
        $others = ($units - 100.00) * 2.25;
        return $first100 + $others;
    }
    else
    {
        $first100 = 100.00 * 2.25;
        $between100And250 = 150.00 * 2.45;
        $others = ($units - 250.00) * 2.68;
        return $first100 + $between100And250 + $others;
    }
};

$salary = $grossSalary($units);

echo "          <td><input name='txtGrossSalary' type='text' value='$salary'></input></td>
        </tr>
      </table>
    </div>
    </form>";
?>

Here is an example of using the webpage:

Introduction to Anonymous Functions

Introduction to Anonymous Functions

As you can see, the concept of anonymous function allows you to declare and use variable whose values can be gotten from complex expressions and conditional statements.

In the same way, instead of one, an anonymous function can take many arguments. As seen with regular functions, the parameters in the parentheses of function are separated with commas. Here is an example of an anonymous function that takes two parameters:

Author Note

Some companies pay their employees (or contractors) on a commission basis. There are various options. For example, a company may apply a base salary plus a percentage based on a certain number of products (or items) sold (or produced).

In the following example, a company pays a commission rate to its employees based on their weekly sales.

<!DOCTYPE html>
<html>
<head>
<title>Products Company</title>
<style type="text/css">

#formulation
{
    margin: auto;
    width:  320pt;
}
#main-title
{
    font-size:   18pt;
    font-weight: bold;
    font-family: Georgia, "Times New Roman", Times, serif;
}
</style>
</head>
<body>

<?php
echo "<form name='frmProducts' method='post'>
      <div id='formulation'>
      <p id='main-title'>Products Company</p>";
      
      $weeklySales =    (float)htmlspecialchars($_POST['txtWeeklySales']);
      $commissionRate = (floaT)htmlspecialchars($_POST['txtCommissionRate']);
      
      $commissionAmount = function($x, $y)
      {
          return $x * $y / 100.00;
      };

      $result = $commissionAmount($weeklySales, $commissionRate);

echo "      <table border='4'>
        <tr>
          <td>Weekly Sales:</td>
          <td>
	    <input name='txtWeeklySales' type='text' value='$weeklySales'></input></td>
        </tr>
        <tr>
          <td>Commission Rate:</td>
          <td>
	    <input name='txtCommissionRate' type='text' style='width: 40px' value='$commissionRate'></input>%
	    <input name='Submit' type='submit' value='Calculate'></input>
          </td>
        </tr>
        <tr>
          <td>Commission Amount:</td>
          <td>
	    <input name='txtCommissionAmount' type='text'
                   value='$result'></input>          </td>
        </tr>
      </table>
    </div>
    </form>";
?>
</body>
</html>

Here is an example of running the program:

Anonymous Functions

Anonymous Functions


Previous Copyright © 2015-2016 FunctionX Next