home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Book HomePHP CookbookSearch this book

Chapter 6. Functions

6.1. Introduction

Functions help you create organized and reusable code. They allow you to abstract out details so your code becomes more flexible and more readable. Without functions, it is impossible to write easily maintainable programs because you're constantly updating identical blocks of code in multiple places and in multiple files.

With a function you pass a number of arguments in and get a value back:

// add two numbers together
function add($a, $b) {
    return $a + $b;

$total = add(2, 2);    // 4

To declare a function, use the function keyword, followed by the name of the function and any parameters in parentheses. To invoke a function, simply use the function name, specifying argument values for any parameters to the function. If the function returns a value, you can assign the result of the function to a variable, as shown in the previous example.

You don't need to predeclare a function before you call it. PHP parses the entire file before it begins executing, so you can intermix function declarations and invocations. You can't, however, redefine a function in PHP. If PHP encounters a function with an identical name to one it's already found, it throws a fatal error and dies.

Sometimes, the standard procedure of passing in a fixed number of arguments and getting one value back doesn't quite fit a particular situation in your code. Maybe you don't know ahead of time exactly how many parameters your function needs to accept. Or, you do know your parameters, but they're almost always the same values, so it's tedious to continue to repass them. Or, you want to return more than one value from your function.

This chapter helps you use PHP to solve these types of problems. We begin by detailing different ways to pass arguments to a function. Recipe 6.2 through Recipe 6.6 cover passing arguments by value, reference, and as named parameters; assigning default parameter values; and functions with a variable number of parameters.

The next four recipes are all about returning values from a function. Recipe 6.7 describes returning by reference, Recipe 6.8 covers returning more than one variable, Recipe 6.9 describes how to skip selected return values, and Recipe 6.10 talks about the best way to return and check for failure from a function. The final three recipes show how to call variable functions, deal with variable scoping problems, and dynamically create a function. There's one recipe on function variables located in Recipe 6.2; if you want a variable to maintain its value between function invocations, see Recipe 5.6.

Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.