Setting Up Default Argument Values


We've seen how to pass data to functions, as in this example, where we're passing a greeting to echo:

 greeting("No worries, your suite is waiting for you."); function greeting($text) {     echo $text, "\n"; } 

This is what you get from this script:

 No worries, your suite is waiting for you. 

But if you forget to pass an argument to this function and call it this way:

 greeting(); 

You'll get this error:

 PHP Warning:  Missing argument 1 for greeting() in C:\php\t.php on line 5 

To avoid this issue, you can give function arguments a default value that is used if you don't supply a value. You do this with the = sign and the default value:

 <?php     greeting();     function greeting($text = "Hi, I hope you have a nice day.")     {         echo $text, "\n";     } ?> 

Now if you call the greeting function with no arguments, you'll see this:

 Hi, I hope you have a nice day. 

If you do pass data to the function, the default value won't be used.

You can give default values to more than one argument, but once you start assigning default values, you have to give them to all arguments that follow as well so that PHP won't get confused if more than one argument is missing. Here's an example:

 function greeting($text1, $text2 = "No ", $text = "worries.") {     echo $text1, $text2, $text3, "\n"; } 

Here's another example, phpdefault.php, Example 4-3the PHP Cruise Lines application, which lets users make reservations. The default reservation is for two passengers in an outside cabin, but other options are OK too, as shown in the script.

Example 4-3. Using default values, phpdefault.php
 <HTML>         <HEAD>             <TITLE>Using default values</TITLE>         </HEAD>         <BODY>             <H1>Using default values</H1>             <?php                 echo "<H1>Welcome to PHP Cruise Lines</H1>";                 book("Steve");                 book("Mary", 1);                 book("Ward", 4, FALSE);                 function book($name, $number = 2, $outside_cabin = TRUE)                 {                     echo "Welcome, $name, you have a reservation for $number" .                     " passengers";                     if($outside_cabin)                         echo " in an outside cabin.";                     else                         echo " in an inside cabin.";                 }             ?>     </BODY> </HTML> 

You can see the results in Figure 4-3.

Figure 4-3. Using default values.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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