A Little KnowledgeIf you've been taking your regular dose of PHP 101, you know now enough about PHP to write simple programs of your own. However, these programs will be "procedural" or linear - the statements in them will be executed sequentially, one after another - simply because that's the only programming style I've used so far. You know what they say about a little knowledge being a dangerous thing... as your PHP scripts become more and more complex, it's only a matter of time before you bump your head against the constraints of the procedural method, and begin looking for a more efficient way of structuring your PHP programs. That's where Part Six of PHP 101 comes in. In this tutorial I'm going to introduce you to a new way of doing things, where code doesn't run in a straight line, but twists, leaps and bounds across the landscape of your script. Most of this activity is accomplished through a programming construct called a "function", and this tutorial teaches you how to build them (once), use them (many times), pass them arguments and have them return values, and generally make your scripts more compact, efficient and maintainable. In Plain EnglishAsk a geek to define the term "function", and he'll probably mumble something about a function being "a block of statements that can be grouped together as a named entity." Since this is a tutorial on PHP, not an introductory course in Greek, I'll translate that for you: a function is simply a set of program statements which perform a specific task, and which can be "called", or executed, from anywhere in your program.
Every programming language comes with its own built-in functions, and typically also allows
developers to define their own functions. For example, if I had a profit statement for the
year on my desk, and I wanted to inflate each number by 35%, I could call my neighborhood
accounting firm and get them to do it for me... or I could write a simple PHP function called
There are three important reasons why functions are a Good Thing™. First: user-defined functions allow you to separate your code into easily identifiable subsections - which are easier to understand and debug. Second: functions make your program modular, allowing you to write a piece of code once and then re-use it multiple times within the same program. And third: functions simplify code updates or changes, because the change needs only to be implemented in a single place (the function definition). Functions thus save time, money and electrons... and I know the electrons at least will thank you! Monday Morning BluesTo see how a function works, look at the following example:
Here's what the output might look like: Hey lady, can you spare a dime?(Sure it's rude, but it does demonstrate how a function allows you to reuse pieces of code.)
The first thing I've done in the script above is define a new function, with the
Of course, defining a function is only half of the puzzle; for it to be of any use at all,
you need to "invoke" it. In PHP, as in a million other languages, this is accomplished
by calling the function by its name, as I've done in the example above. Calling a
user-defined function is identical to calling a built-in PHP function like Here's the typical format for a function:
Having an Argument... or TwoFunctions like the one you saw in the previous section print the same value every time you invoke them. While this is interesting the first six times, it can get boring on the seventh. What we need to do, to make these boring, unintelligent functions a little more exciting, is get them to return a different value each time they are invoked. Enter arguments. Arguments work by using a placeholder to represent a certain variable within a function. Values for this variable are provided to the function at run-time from the main program. Since the input to the function will differ at each invocation, so will the output. To see how this works, look at the following function, which accepts a single argument and then prints it back after a calculation:
In this example, when the It's also possible to pass more than one argument to a function. This is done using a comma-separated list, as the following example shows:
Here, depending on the value of the second argument, program flow within the function moves to the appropriate branch and manipulates the first argument. Note that there is no requirement to specify the data type of the argument being passed to a function. Since PHP is a dynamically-typed language, it automatically identifies the variable type and acts on it appropriately. Circles in the Sand
The functions on the previous page simply printed their output to the screen. But what
if you want the function to do something else with the result? Well, in PHP, you can
have a function return a value, such as the result of a calculation, to the statement
that called it. This is done using a
Here, the argument passed to the You can even use the result of a function inside another function, as illustrated in this minor revision of the example above:
Return values need not be numbers or strings alone: a function can just as easily return an array (remember them?), as demonstrated in the following example:
Assuming the file looked like this, test@test.comthe output of the script above would look like this: test.com, x.com, deeply.bored.org, where.ami.net,Note that the return statement terminates program execution inside a function. Marching OrderThe order in which arguments are passed to a function can be important. The following example requires that the name is passed as the first argument, and the place as the second.
This is the output: Hello, I am Moonface from The Faraway TreeIn this example, if you reversed the order in which arguments were passed to the function, this is what you'd see: Hello, I am The Faraway Tree from MoonfaceAnd look what happens if you forget to pass a required argument altogether: Warning: Missing argument 2 for introduce() in xx.php on line 3In order to avoid such errors, PHP allows you to specify default values for all the arguments in a user-defined function. These default values are used if the function invocation is missing some arguments. Here's an example:
In this case the output would be: Hello, I am Moonface from LondonNotice that the function has been called with only a single argument, even though the function definition requires two. However, since default values are present for each argument in the function, the missing argument is replaced by the default value for that argument, and no error is generated. The Amazing Shrinking Argument List
All the examples on the previous page have one thing in common: the number of arguments
in the function definition is fixed. However, PHP 4.x also supports variable-length
argument lists, by using the
Hmmm... if you're sneaky, you might have tried to pass
Going GlobalLet's now talk a little bit about the variables used within a function, and their relationship with variables in the outside world. Usually, the variables used within a function are "local" - meaning that the values assigned to them, and the changes made to them, are restricted to the function space alone. Consider this simple example:
When you run this script, here is what you will see: It is Saturday inside the functionIn other words, the variable inside the function is insulated from the identically-named variable in the main program. Variables inside a function are thus aptly called "local" variables because they only exist within the function in which they are defined. The reverse is also true: variables defined inside a function cannot be "seen" outside it. To illustrate, take a look at the next example and its output (or the lack of it):
Here is the output: Today isDepending on the error_reporting you have set up in php.ini, you might also see an error message: Notice: Undefined variable: today in x1.php on line 10
However, I didn't say this can't be overcome. To have variables within a function accessible
from outside it (and vice-versa), all you need to do is first declare them "global" with
the - you guessed it! -
Here is a rewrite of the earlier example, this time declaring the
And here is the output: It is Tuesday before running the functionThus, once a variable is declared global, it is available at the global level, and can be manipulated both inside and outside a function.
PHP also comes with so-called superglobal variables - variables that are always available,
regardless of whether you're inside a function or outside it. You've already seen some of
these special variables in action: the Superglobals are a Good Thing™, because they're always there when you need them, and you don't need to jump through any hoops to use the data stored inside them. Read more about superglobals and variable scope at http://www.php.net/manual/en/language.variables.predefined.php and http://www.php.net/manual/en/language.variables.scope.php. Checking ReferencesAny discussion about variables in and out of functions would be incomplete without some mention of the difference between "passing by reference" and "passing by value". So far, all the examples you've seen have involved passing arguments to a function "by value" - meaning that a copy of the variable was passed to the function, while the original variable remained untouched. However, PHP also allows you to pass "by reference" - meaning that instead of passing a value to a function, you pass a reference to the original variable, and have the function act on that instead of a copy. Confusing? Well, this is probably easier to understand with an example. Let's start with this:
You've already seen this before, and you already know what the output is going to say: It is Tuesday inside the functionThis is because when the getDay() function is invoked, it passes the value
"Saturday" to the function ("passing by value"). The original variable remains untouched;
only its content is sent to the function. The function then acts on the content, modifying
and displaying it.
Now, look at how "passing by reference" works:
Notice the ampersand (&) before the argument in the function definition. This tells PHP to use the variable reference instead of the variable value. When such a reference is passed to a function, the code inside the function acts on the reference, and modifies the content of the original variable (which the reference is pointing to) rather than a copy. If you then try retrieving the value of the original variable outside the function, it returns the modified value: .Now you understand why I said no discussion about variables would be complete without mentioning the two ways of passing variables. This, of course, is what the global keyword does inside a function: use a reference to ensure that changes
to the variable inside the function also reflect outside it. The PHP manual puts it best
when it says "...when you declare a variable as global $var you are in fact
creating a reference to a global variable". For more examples, read all about references
at http://www.zend.com/manual/language.references.php.
And that just about concludes this tutorial. This time you've taken a big step towards better software design by learning how to abstract parts of your PHP code into reusable functions. You now know how to add flexibility to your functions by allowing them to accept different arguments, and how to obtain one (or more) return values from them. Finally, you've learned a little bit about how PHP treats variables inside and outside functions. In Part Seven, I'll be showing you how to group related functions together into classes, and also telling you all about the cool new features in the PHP 5 object model. You definitely don't want to miss that one! |