O'Reilly logo

PHP: The Good Parts by Peter MacIntyre

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 more aspects ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required