|< Day Day Up >|
Chapter 5. Functions
When you're writing computer programs, laziness is a virtue. Reusing code you've already written makes it easier to do as little work as possible. Functions are the key to code reuse. A function is a named set of statements that you can execute just by invoking the function name instead of retyping the statements. This saves time and prevents errors. Plus, functions make it easier to use code that other people have written (as you've discovered by using the built-in functions written by the authors of the PHP interpreter).
The basics of defining your own functions and using them are laid out in Section 5.1. When you call a function, you can hand it some values with which to operate. For example, if you write a function to check whether a user is allowed to access the current web page, you would need to provide the username and the current web page name to the function. These values are called arguments. Section 5.2 explains how to write functions that accept arguments and how to use the arguments from inside the function.
Some functions are one-way streets. You may pass them arguments, but you don't get anything back. A print_header( ) function that prints the top of an HTML page may take an argument containing the page title, but it doesn't give you any information after it executes. It just displays output. Most functions move information in two directions. The access control function mentioned above is an example of this. The function gives you back a value: true (access granted) or false (access denied). This value is called the return value. You can use the return value of a function like any other value or variable. Return values are discussed in Section 5.3.
The statements inside a function can use variables just like statements outside a function. However, the variables inside a function and outside a function live in two separate worlds. The PHP interpreter treats a variable called $name inside a function and a variable called $name outside a function as two unrelated variables. Section 5.4 explains the rules about which variables are usable in which parts of your programs. It's important to understand these rules ?get them wrong and your code relies on uninitialized or incorrect variables. That's a bug that is hard to track down.
|< Day Day Up >|