6.2. Setting Default Values for Function Parameters

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.

Solution

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

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

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

Get PHP Cookbook 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.