TechniqueSpecify the default value in the function declaration, like so: <?php function log_message($message, $prefix="GENERAL") { print "$prefix: $message\n"; } log_message("Startup"); /* logs "GENERAL: Startup" */ log_message("Cannot open file", "ERROR"); /* logs "ERROR: Cannot open file" */ ?> CommentsAs discussed in the introduction, you can pass arguments to a function simply by declaring them as variables within the parentheses. If you want to establish a default value for variables , you simply assign it the default value within the parentheses. If no argument is specified when the function is called, the default value for the argument will be used. An argument without a default value is required to be present at call time. By setting a default value, you make the argument optional even if you set the default value to empty, like so: function say_hello ($name='') { print "hello"; if (!empty($name)) { print ", $name"; } } The function say_hello() can now be called as say_hello() or say_hello("Erin Keiser-Clark") , and it will behave accordingly . The arguments with default values have to be declared at the end of the argument list. Therefore, the following declaration is illegal: function log_message($prefix = "GENERAL", $message) { } The expression used as a default value has to be constant ”using a variable, an array of variables, or a function call is illegal. Note that in PHP 4, it is possible to specify a NULL value as the default. The result would be as if the argument were not set at all ”it will fail the isset() test. This can be useful in certain situations, such as where an empty string '' would actually be a valid value. |