Chapter 11: Using Functions

Google

Why use functions?

There are two main reasons for using functions:

Functions break your program into smaller chunks and make it easier to read. When you look at the main body and see a function call ( Ex: myFunc(arg1, arg2) ), you can scroll down to where the function is and see what the code inside the function is doing. Then you can go back to where the function was called and see what's being done with the value that the function was supposed to return.

Finally, look at the code that comes after the function and see what's supposed to happen next. Ask yourself what would get messed up if the function returned the wrong value. Hopefully, you've already tested the function to make sure it always returns a correct value - or at least one that makes sense.

Functions let you use one block of code to do the same task many times. This keeps you from having to write the same instructions over and over. You can take a function that performed well in one program and use it an another program where you need to do the same job.

Where do I get functions?

As I just said, you can recycle them from other programs you've written. You can copy and paste them from other programs you've obtained elsewhere. You'll find some of my favorites included with this book. See Appendix C for a list of these.

Visit some of the sites listed in Chapter 3. Download some of the free scripts that sound interesting or useful. You're bound to find some cool functions. They may be usable exactly as written. You may need to make minor adjustments. The good news is that there's a nearly endless supply of them!


How do I use functions?

It doesn't get much easier than this! Put them at the bottom of the script and then call them whenever you need to perform the tasks they do. A function is called by a line that looks like this:

write_data();

Or this:

$result = write_data();

... where "write_data" is the name of the function. This was covered in Chapter 6 in a little more detail. If you skipped that chapter, please go back and read it now. Otherwise, just check out the functions that come with the book. There's a brief description of each one in Appendix C. Also, read the comments within the functions themselves. This can give you more insight into how to use each one.

Note: Sometimes you'll use the result (return value) of a function in a if-statement. Most functions have a return statement at the end. It usually takes the form:

return $variable; OR return;

Parentheses around the value to be returned are optional unless you're returning a string. The value returned is the final "result" of running the function. Your code might call another function. Many times the return value of the first function is tested and used to decide whether to call the other function. For example:

if (bad_data()) {ShowError();}

Tip: Include a return statement in each function even if you don't plan to use the return value. You may find a use for it later. If you do, a simple text search for the word "return" will take you to the return statement. There you can change or add the return value.

You may want to write several functions like this to perform filtering on various kinds of inputs. Then you can put them all in a single PHP file and just "include" it when you write scripts to handle forms. Any script that "includes" the file will have access to all of its functions. You only have to write them once, add one line to a new script and Voila! Your code is simplified a lot.

Suppose that in your form-handling script you wanted to filter unwanted characters from a phone number. You've written a function to do this job and put it in filters.php. That function might be named filter_phone($Phone). You simply add this line at or near the top of the new script:

include ("filters.php");

Now, when you need to filter phone, fax and cell phone numbers, you can write these lines:

$phone = filter_phone($phone);
$fax = filter_phone($fax);
$cell = filter_phone($cell);

A good practice is to place the include() statements at the top of the script. Be aware that there are exceptions, though! For instance, a file that holds a bunch of HTML code you plan to re-use a lot can be "included" but you'll need to be sure that it's placed exactly where you want that block of HTML to appear on the page. Like this:

<?php
$content = "A bunch of HTML to display content that is unique to this web page...";
include("header.html");
// header.html might contain the opening HTML tag, the HEAD
// section and the first parts of a table...
echo ("$content");
include("footer");
?>

The files header.html and footer.html will drop HTML code onto the page before and after the code in $content is echoed to the screen. So if you don't put them in the right places in your PHP file, the page will be messed up.

I'm sure you can see from this example that when you include() an HTML file, it doesn't have to be a complete we page. It can be any chunk of HTML you want to drop in. Now for another clever trick...

A file named "whatever.php" can be include()d. But because it's a PHP file, in can have it's own include()s inside it! Think about that for a few seconds...I'll wait. OK. Here's why that's so cool. Suppose you have a lot of pages with a lot of elements in common - but some are a little different.

You can make several include files and name them include1.php, include2,php, etc. Inside each of them you could include() one or more .html files, .txt files, etc. Web pages that needed only the stuff you packed into include1.php would use include("include1.php"); and pages that needed only what was in include2.php would use include("include2.php");

If you want to, go back to chapter 10 and look at the code I gave you for filtering various inputs. You could take each of those little chunks of code and make it into a function. Put all those little functions into filters.php and you'll have a new general-purpose filter set. Add any new ones you create and always include filters.php when you write a new form handler. That's a real time-saver.

Another advantage of this technique is that it will reduce your test time. Once you've proven to yourself that your filters work exactly right on one form, you won't have to test them any more. If something goes wrong in a new form-handling script, check to be sure that your function calls are correct and that the right variables are being passed to the filter functions.

If a new form has an input you've never used before, write a filter for it and add it to filters.php. Test the living daylights out of it. Then you'll never have to write it again. Apply the same kind of thinking and action to other functions you intend to use over and over.

Group related functions into separate files and give each file a meaningful name. You might want to write a set of functions to do database operations. With practice, you'll be able to write new scripts faster and faster, since you don't have to keep writing them "from scratch." It doesn't matter whether you wrote all the functions yourself or not - as long as you're sure they all work right!

Previous Page   Table of Contents   Next Page

Copyright © 2004 Steve Humphrey