Chapter 3. Functions (Doing It Once)

PHP uses functions, much like any other programming language, and it certainly is to your advantage to get to know how to make the most of them.

PHP defines functions in two ways: those that return a value and those that do not. Functions should stand alone from other segments of code as much as possible. The rules for defining a function are fairly simple; you designate a function using its reserved word, giving it a unique name beginning with a letter or an underscore character, followed by any number of letters, underscores, or numbers. Round brackets (()) follow the function name—these are used to pass in any parameters that govern the function (more on that later). Finally, use curly braces ({}) to surround any code that is to be contained within the function.

Here is a sample function:

function MyFunction ( ) {
    echo "This is being displayed because MyFunction has been called" ;
}

There is a difference between defining a function and calling one into action. The code above merely defines the function called MyFunction; it does not call it or activate it. Here is some code defining the function and then calling it:

function MyFunction ( ) {
    echo "This is being displayed because MyFunction has been called" ;
}

MyFunction () ;

If you are not expecting any value to be returned, the code above will work fine. It will simply print the string, “This is being displayed because MyFunction has been called.”

Parameter Passing

Let’s look at a few ...

Get PHP: The Good Parts now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.