O'Reilly logo

Learning PHP 5 by David Sklar

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

Passing Arguments to Functions

While some functions (such as page_header( ) in the previous section) always do the same thing, other functions operate on input that can change. The input values supplied to a function are called arguments. Arguments add to the power of functions because they make functions more flexible. You can modify page_header( ) to take an argument that holds the page color. The modified function declaration is shown in Example 5-4.

Example 5-4. Declaring a function with an argument

function page_header2($color) {
    print '<html><head><title>Welcome to my site</title></head>';
    print '<body bgcolor="#' . $color . '">';
}

In the function declaration, you add $color between the parentheses after the function name. This lets the code inside the function use a variable called $color, which holds the value passed to the function when it is called. For example, you can call the function like this:

page_header2('cc00cc');

This sets $color to cc00cc inside page_header2( ), so it prints:

<html><head><title>Welcome to my site</title></head><body bgcolor="#cc00cc">

When you define a function that takes an argument as in Example 5-4, you must pass an argument to the function when you call it. If you call the function without a value for the argument, the PHP interpreter complains with a warning. For example, if you call page_header2( ) like this:

page_header2( );

The interpreter prints a message that looks like this:

PHP Warning:  Missing argument 1 for page_header2( )

To avoid this ...

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