start page | rating of books | rating of authors | reviews | copyrights

Book HomePHP CookbookSearch this book

6.3. Setting Default Values for Function Parameters

6.3.1. Problem

You want a parameter to have a default value if the function's caller doesn't pass it. For example, a function to draw a table might have a parameter for border width, which defaults to 1 if no width is given.

6.3.2. Solution

Assign the default value to the parameters inside the function prototype:

function wrap_html_tag($string, $tag = 'b') {
    return "<$tag>$string</$tag>";
}

6.3.3. Discussion

The example in the Solution sets the default tag value to b, for bold. For example:

$string = 'I am some HTML';
wrap_html_tag($string);

returns:

<b>I am some HTML</b>

This example:

wrap_html_tag($string, 'i');

returns:

<i>I am some HTML</i>

There are two important things to remember when assigning default values. First, all parameters with default values must appear after parameters without defaults. Otherwise, PHP can't tell which parameters are omitted and should take the default value, and which arguments are overriding the default. So, wrap_html_tag( ) can't be defined as:

function wrap_html_tag($tag = 'i', $string)

If you do this and pass wrap_html_tag( ) only a single argument, PHP assigns the value to $tag and issues a warning complaining of a missing second argument.

Second, the assigned value must be a constant — a string or a number. It can't be a variable. Again, using wrap_html_tag( ) as our example, you can't do this:

$my_favorite_html_tag = 'i';

function wrap_html_tag($string, $tag = $my_favorite_html_tag) {
    ...
}

If you want to assign a default of nothing, one solution is to assign the empty string to your parameter:

function wrap_html_tag($string, $tag = '') {
    if (empty($tag)) return $string;
    return "<$tag>$string</$tag>";
}

This function returns the original string, if no value is passed in for the $tag. Or, if a (nonempty) tag is passed in, it returns the string wrapped inside of tags.

Depending on circumstances, another option for the $tag default value is either 0 or NULL. In wrap_html_tag( ), you don't want to allow an empty valued-tag. However, in some cases, the empty string can be an acceptable option. For instance, join( ) is often called on the empty string, after calling file( ), to place a file into a string. Also, as the following code shows, you can use a default message if no argument is provided but an empty message if the empty string is passed:

function pc_log_db_error($message = NULL) {
    if (is_null($message)) {
        $message = 'Couldn't connect to DB';
    }

    error_log("[DB] [$message]");
}

6.3.4. See Also

Recipe 6.6 on creating functions that take a variable number of arguments.



Library Navigation Links

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