PHP Functions
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 wrap text in an HTML tag might have a parameter for the tag name, which defaults to strong if none is given.Solution
Assign the default value to the parameters inside the function prototype:function wrap_in_html_tag($text, $tag = 'strong') {
return "<$tag>$text</$tag>";
}
Discussion
The example in the Solution sets the default tag value to strong. For example:print wrap_in_html_tag("Hey, a mountain lion!");
prints:
<strong>Hey, a mountain lion!</strong>
This example:
print wrap_in_html_tag("Look over there!", "em");
prints:
<em>Look over there!</em>
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_in_html_tag() can’t be defined as:
function wrap_in_html_tag($tag = 'strong', $text)
If you do this and pass wrap_in_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_in_html_tag(), such as our example, you can’t do this:
$my_favorite_html_tag = 'blink';
function wrap_in_html_tag($text, $tag = $my_favorite_html_tag) {
return "<$tag>$text</$tag>";
}
If you want to assign a default of nothing, one solution is to assign the empty string to your parameter:
function wrap_in_html_tag($text, $tag = '') {
if (empty($tag)) { return $text; }
return "<$tag>$text</$tag>";
}
This function returns the original string, if no value is passed in for the $tag. 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_in_html_tag(), you don’t want to allow an empty-valued tag. However, in some cases, the empty string can be an acceptable option. 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 log_db_error($message = NULL) {
if (is_null($message)) {
$message = "Couldn't connect to DB";
}
error_log("[DB] [$message]");
}
No comments:
Post a Comment