PHP functions

See more about:

Where are we?

You know how to run a bunch o’ validation in PHP. We can improve the code by using functions. Let’s see how.

This lesson’s goals

By the end of this lesson, you should:

  • Know what a function is.
  • Know why functions are Good Things.
  • Be able to create a function library.

What is a function?

A function is a piece of code that has three things:

  • A name, e.g., validate_order, or compute_area.
  • Some data going in (optional).
  • Some data coming out (optional).

Functions do three Good Things for us.

  • They reduce duplicate code, making Web sites easier to maintain.
  • They let us create reusable libraries we can drop into any page.
  • They clump PHP statements together, making a program easier to understand.

Let’s see an example. Here’s a page that computes the area of some rectangles.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Rectangle Areas</title>
  </head>
  <body>
    <h1>Rectangle Areas</h1>
    <?php
    $r1_width = 7;
    $r1_length = 3;
    $r1_area = rectangle_area($r1_width, $r1_length);
    print "<p>A rectangle with sides of $r1_width and $r1_length has an area of $r1_area.</p>";
    
    $r2_width = 5;
    $r2_length = 6;
    $r2_area = rectangle_area($r2_width, $r2_length);
    print "<p>A rectangle with sides of $r2_width and $r2_length has an area of $r2_area.</p>";
    
    function rectangle_area($width, $length) {
      $area = $width * $length;
      return $area;
    }
    ?>
  </body>
</html>

Figure 1. Area code

The functions starts in line 20. Its name is rectangle_area. It has two input parameters: $width, and $length. The return statement stops the function, and sends back some data.

A function call sends some data to the function, and (maybe) does something with the result that comes back from the function’s return statement. For example:

$r1_area = rectangle_area($r1_width, $r1_length);

The values in $r1_width and $r1_length go into the function. The return statement sends back a result, which gets stored in $r1_area.

The arguments in the call and the function match by position, not name.

Argument matching

Figure 2. Argument matching

That’s why the function can be called with different variables each time.

You can try the program.

Here’s part of Figure 1 again:

<?php
$r1_width = 7;
$r1_length = 3;
$r1_area = rectangle_area($r1_width, $r1_length);
print "<p>A rectangle with sides of $r1_width and $r1_length has an area of $r1_area.</p>";

$r2_width = 5;
$r2_length = 6;
$r2_area = rectangle_area($r2_width, $r2_length);
print "<p>A rectangle with sides of $r2_width and $r2_length has an area of $r2_area.</p>";

function rectangle_area($width, $length) {
  $area = $width * $length;
  return $area;
}
?>

Figure 1 (again). Area code

The function is after the rest of the code on the page. But it can be in other places as well. For example, it could be above the other code, like this:

<?php
function rectangle_area($width, $length) {
  $area = $width * $length;
  return $area;
}

$r1_width = 7;
$r1_length = 3;
$r1_area = rectangle_area($r1_width, $r1_length);
print "<p>A rectangle with sides of $r1_width and $r1_length has an area of $r1_area.</p>";

$r2_width = 5;
$r2_length = 6;
$r2_area = rectangle_area($r2_width, $r2_length);
print "<p>A rectangle with sides of $r2_width and $r2_length has an area of $r2_area.</p>";
?>

Figure 3. Moving the function up

Or it could be in the middle:

<?php
$r1_width = 7;
$r1_length = 3;
$r1_area = rectangle_area($r1_width, $r1_length);
print "<p>A rectangle with sides of $r1_width and $r1_length has an area of $r1_area.</p>";

function rectangle_area($width, $length) {
  $area = $width * $length;
  return $area;
}

$r2_width = 5;
$r2_length = 6;
$r2_area = rectangle_area($r2_width, $r2_length);
print "<p>A rectangle with sides of $r2_width and $r2_length has an area of $r2_area.</p>";
?>

Figure 4. Moving the function to the middle

The function can even be in another file. As we’ll see.

Creating a function library

The function rectangle_area works, but is so simple that it is hardly worth using. Let’s change things by:

  • Creating a more complex function.
  • Moving the function into a library file.

Here is the page:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Normal probability density function</title>
  </head>
  <body>
    <?php
    require 'normal-pdf.inc';
    print normal_pdf(.5, 0, 1);
    ?>
  </body>
</html>

Figure 5. Another example

Line 10 calls a function called normal_pdf and sends it three arguments. It prints the return value. Note that you can do anything with the return value: print it, put it in a variable, use it in an if statement, and so on.

The function isn’t in Figure 5. It’s in a separate file, normal-pdf.inc. Here’s the contents of that file.

<?php
function normal_pdf($x, $mu, $sigma) {
  $denominator = sqrt(2 * pi()) * $sigma;
  $numerator = exp(-($x - $mu) * ($x - $mu) / ( 2 * $sigma));
  $density = $numerator / $denominator;
  return $density;
}
?>

Figure 6. The function

Being in a separate file, it can be inserted into any number of PHP pages. And it’s a lot more complex than rectangle_area.

The function returns a probability value from a normal distribution. It was adapted from code on this page.

When variables are created inside a function, they are called “local variables.” They are not available outside the function. They are destroyed when the function exits. So if you tried to print the variable $denominator outside the function, you would get an error. It only exists inside the function.

This is a Good Thing. It means you can write a program like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Normal probability density function</title>
  </head>
  <body>
    <?php
    require 'normal-pdf.inc';
    $numerator = 1;
    $denominator = 2;
    $p = normal_pdf($numerator/$denominator, 0, 1);
    ?>
    <p>Numerator: <?php print $numerator; ?></p>
    <p>Denominator: <?php print $denominator; ?></p>
    <p>p: <?php print $p; ?></p>
  </body>
</html>

Figure 7. Local variables in action

If you try the program, you will see that it works. Neither $numerator nor $denominator – names that appear in both the function and the code that calls it – get clobbered.

Why is there no confusion between $numerator in line 10 of Figure 7, and $numerator in line 4 of the inserted file, shown in Figure 6? When the function normal_pdf runs, it creates a new $numerator variable all of its own. It gets wiped out when the function exits.

Why is this a Good Thing? Because it makes it easier to use function libraries. You can insert normal-pdf.inc into any PHP file you want, without worrying about whether variables will get hurt. W00f!

String functions

Here’s another one:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Farm animal plurals</title>
  </head>
  <body>
    <h1>Farm animal plurals</h1>
    <p>The plural of "dog" is <?php print farm_animal_plural('dog'); ?>.</p>
    <p>The plural of "cat" is <?php print farm_animal_plural('cat'); ?>.</p>
    <p>The plural of "goose" is <?php print farm_animal_plural('goose'); ?>.</p>
    <?php
    function farm_animal_plural($animal) {
      if ( $animal == 'sheep' ) {
        return 'sheep';
      }
      if ( $animal == 'goose' ) {
        return 'geese';
      }
      if ( $animal == 'fish' ) {
        return 'fish';
      }
      return $animal . 's';
    }
    ?>
  </body>
</html>

Figure 8. String function

The function takes the name of a farm animal, and returns the plural. It deals with a few special cases, and then just returns the input value, with an “s” attached.

It isn’t a very good function.

Some things to notice about this example:

  • There are many return statements. As soon as one is encountered, PHP exits.
  • You can return any value, not just a plain variable. Line 23 attaches something to a variable before returning it.
  • You can output the return value of a function directly. You don’t need to put it in a variable first. Lines 9, 10, and 11 do this.

Summary

This lesson explains:

  • What a function is.
  • Why functions are Good Things.
  • How to create a function library.

What now?

Let’s see how you can write a PHP validation function.


How to...

Lessons

User login

Log in problems? Try here


Dogs