Recipe 6.2. Setting Default Values for Function Parameters

6.2.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.2.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.2.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);


<b>I am some HTML</b>

This example:

wrap_html_tag($string, 'i');


<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, such as a string or a number. It can't be a variable. Again, using wrap_html_tag( ), such 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.2.4. See Also

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

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445 © 2008-2017.
If you may any questions please contact us: