6.3. Setting Default Values for Function Parameters6.3.1. ProblemYou 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. SolutionAssign the default value to the parameters inside the function prototype: function wrap_html_tag($string, $tag = 'b') { return "<$tag>$string</$tag>"; } 6.3.3. DiscussionThe 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 AlsoRecipe 6.6 on creating functions that take a variable number of arguments. Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|