Chapter 11: Using Functions |
|
What is a function, anyway? | |
|
In PHP, as in many other languages, a function is a separate block of code designed to do a particular job. When we want to do that job somewhere in a script, we "invoke" or "call" the function by using its name. You can do this anywhere in the script, even inside another function. That's known as "nesting" functions. Functions can be placed anywhere in a script. They are available to any code in the script that needs to call them. Note: Be careful when you mix normal HTML and more than one block of PHP code in a single file. A function you wrote that exists in one block won't necessarily be available to a different PHP block. A good practice is to make the whole file one PHP script, with calls to the echo() function to display "chunks" of HTML code in the browser. Or put all the PHP code in one block and put any HTML code that won't be affected by the script outside of the PHP block (before it or after it or both). Here's an example: |
|
<HTML>
Here's an example of a function. It begins with the word function, an argument list (variables that will be passed to the function when it's called) and a left curly-brace. Then there are a few lines of code, followed by a right curly-brace. This function takes one argument, $item. It replaces certain characters in $item and returns the newly-processed $item. function cleanup ($item) { Look closely at the lines of code inside this function. You'll see that except for the return statement they are all calls to other functions. This is an example of "nesting" one or more functions inside another function. The functions that are nested inside this one are all built-in functions. That means that you don't have to write the code for them - PHP already knows about them. Note: The argument list can be empty. Sometimes a function needs no variables passed in from outside in order to do its job. When the argument list is empty, the parentheses are optional. So myFunction(); is the same as myFunction; - if its argument list is empty. |
| Previous Page Table of Contents Next Page |
Copyright © 2004 Steve Humphrey |