8.1 Passing a Default Value to a Function


You want to pass an argument to a function, but you want to make the argument optional by providing a default value.

Technique

Specify 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" */ ?> 

Comments

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



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net