Working with Functions


On the face of it, functions work much the same in PHP as in JavaScript. Here’s how a function is set up:

 function function_name([argument_list...]) {     [statements;]     [return return_value;] }

It’s easiest to see this with examples. For instance, you might want to use a function to display a copyright symbol at the bottom of your Web pages. You would start by displaying the Web page content like this:

 <html>    <head>      <title>Using functions to create a copyright mark</title>    </head>        <body>      <h1>Using functions to create a copyright mark</h1>      <?        echo "<h3>Welcome to my web page!</h3>";        echo "<br>";        echo "How do you like it?";        echo "<br>";        echo "<br>";          .          .          .      ?>    </body> </html>

Then you call the function in this example, print_copyright, to print the copyright symbol:

 <html>   <head>     <title>Using functions to create a copyright mark</title>   </head>   <body>     <h1>Using functions to create a copyright mark</h1>     <?       echo "<h3>Welcome to my web page!</h3>";       echo "<br>";       echo "How do you like it?";       echo "<br>";       echo "<br>";       print_copyright();       .       .       .     ?>   </body> </html>

The print_copyright function prints the copyright to the Web page when called, as you see here:

 <html>   <head>     <title>Using functions to create a copyright mark</title>   </head>      <body>     <h1>Using functions to create a copyright mark</h1>     <?       echo "<h3>Welcome to my web page!</h3>";       echo "<br>";       echo "How do you like it?";       echo "<br>";       echo "<br>";       print_copyright();       function print_copyright()       {         echo "<hr>";         echo "<center>";         echo "&copy; 2007 PHP Masters, Inc.";         echo "</center>";       }     ?>   </body> </html>

You can see the copyright mark at the bottom of the Web page, functions.php, shown in Figure 13.1.

image from book
Figure 13.1: The functions.php application

And, as with JavaScript, you can pass data to functions in PHP as well, which is discussed in the next section.

Passing data to functions

Arguments are passed to functions in the argument list, which is a comma-separated list of data items, as shown here:

 function function_name([argument_list...]) {     [statements;]     [return return_value;] }

For example, let’s say you wanted to customize the copyright message you display, passing the date and copyright holder to the function. You could pass that data to the function like this in passData.php:

 <html>  <head>    <title>Passing data to functions</title>  </head>  <body>    <h1>Passing data to functions</h1>    <?      echo "<h3>Welcome to my web page!</h3>";      echo "<br>";      echo "How do you like it?";      echo "<br>";      echo "<br>";      $date = "2007";      $holder = "PHP Masters, Inc.";      print_copyright($date, $holder);        .        .        .    ?>  </body> </html>

and you can read the passed data in the print_copyright function this way:

 <html>  <head>    <title>Passing data to functions</title>  </head>    <body>    <h1>Passing data to functions</h1>    <?      echo "<h3>Welcome to my web page!</h3>";      echo "<br>";      echo "How do you like it?";      echo "<br>";      echo "<br>";      $date = "2007";      $holder = "PHP Masters, Inc.";      print_copyright($date, $holder);      function print_copyright($copyright_date,        $copyright_holder)      {        echo "<hr>";        echo "<center>";        echo "&copy; $copyright_date $copyright_holder";        echo "</center>";      }    ?>  </body> </html>

The results are shown in Figure 13.2.

image from book
Figure 13.2: The passData.php application

Setting up default arguments

In PHP, you can also set up default arguments.

The print_copyright function displays two items, $copyright_date and $copyright_holder:

 function print_copyright($copyright_date,   $copyright_holder) {   echo "<hr>";   echo "<center>";   echo "&copy; $copyright_date $copyright_holder";   echo "</center>"; }

But what if you were to pass only one data item to the function, such as only the date?

 <html>    <head>      <title>Passing data to functions</title>    </head>    <body>     <h1>Passing data to functions</h1>     <?       echo "<h3>Welcome to my web page!</h3>";       echo "<br>";       echo "How do you like it?";       echo "<br>";       echo "<br>";       $date = "2007";       print_copyright($date);         .         .         .     ?>   </body> </html>

Normally, that would be a problem, of course, but not if you set up a default argument for the copyright holder. You do that in the argument list with an equal sign and the default value you want the argument to have if no other argument was assigned, like this:

 <html>   <head>     <title>Passing data to functions</title>   </head>      <body>     <h1>Passing data to functions</h1>     <?       echo "<h3>Welcome to my web page!</h3>";       echo "<br>";       echo "How do you like it?";       echo "<br>";       echo "<br>";       $date = "2007";       print_copyright($date);              function print_copyright($copyright_date,         $copyright_holder = "PHP Masters, Inc.")       {         echo "<hr>";         echo "<center>";         echo "&copy; $copyright_date $copyright_holder";         echo "</center>";       }     ?>   </body> </html>

The results are the same as the results shown in Figure 13.2, but this time, the copyright holder is supplied by the default argument.

Note 

You can supply default values for as many arguments as you want, but if you supply a default value for a particular argument, you must supply a default argument for all the following arguments in the argument list as well; otherwise, PHP would not be able to figure out which argument your default value is meant for.

Creating variable-length argument lists

You can also pass variable-length argument lists to functions. This is not the same as setting up default arguments; in this case, you can call the same function with a different number of arguments, and you can retrieve all the arguments using special functions instead of giving each argument a default value. You can pass as many arguments as you want.

For example, if you have a function named combiner that joins strings together, you might call it like this:

 combiner("No", "problems"); combiner("No", "problems", "here."); combiner("No", "problems", "at", "all.");

In the combiner function, you can use three PHP functions to get the number of arguments passed to you, a single argument that you specify by number, and an array that holds all the arguments passed to you. Here are those functions:

  • func_num_args: Returns the number of arguments passed

  • func_get_arg: Returns a single argument

  • func_get_args: Returns all arguments in an array

Here’s what the combiner function might look like using func_get_args to get all the passed arguments in an array:

 function combiner() {     $arg_list = func_get_args();         .         .         . }

Then you can loop over the number of arguments passed, which you can find with func_num_args this way:

 function combiner() {     $arg_list = func_get_args();          for ($loop_index = 0;$loop_index < func_num_args();       $loop_index++) {                                                                          .         .         .     } }

You can combine the passed text into a single text string:

 function combiner() {     $text_string = "";     $arg_list = func_get_args();     for ($loop_index = 0;$loop_index < func_num_args();       $loop_index++) {       $text_string .= $arg_list[$loop_index] . "";     }     .     .     . }

and all that’s left is to echo the combined text string:

 function combiner() {     $text_string = "";     $arg_list = func_get_args();          for ($loop_index = 0;$loop_index < func_num_args();       $loop_index++) {       $text_string .= $arg_list[$loop_index] . " ";     }     echo $text_string; }

You can see this function at work in variableArguments.php:

 <html>   <head>     <title>       Using variable-length argument lists     </title>   </head>      <body>     <h1>Using variable-length argument lists</h1>             <?     echo "combiner(No, problems) =                                ", combiner("No",       "problems"), "<br>";     echo "combiner(No, problems, here.) =                         ",       combiner("No", "problems", "here."), "<br>";       echo "combiner(No, problems, at, all.) =                      ",       combiner("No", "problems", "at", "all."), "<br>";     function combiner()     {       $text_string = "";       $arg_list = func_get_args();       for ($loop_index = 0;$loop_index < func_num_args();         $loop_index++) {         $text_string .= $arg_list[$loop_index] . " ";       }       echo $text_string;     }     ?>   </body> </html>

The results appear in Figure 13.3, where all the arguments passed to the combiner function are used.

image from book
Figure 13.3: The variableArguments.php application

Returning values from functions

You can also return values from functions in PHP. To return a value from a PHP function, all you have to do is to use the return statement, which looks like this:

 return (value);

The parentheses are optional; you can also use the return statement like this:

 return value;

For example, you might have a function named adder that takes two numbers and returns their sum; here’s what that looks like in adder.php:

 <html>   <head>     <title>       Returning values from functions     </title>   </head>      <body>     <h1>Returning values from functions</h1>     <?       echo "adder(3, 2) = ", adder(3, 2), "<br>";       echo "adder(5, 7) = ", adder(5, 7), "<br>";       echo "adder(9, 17) = ", adder(9, 17), "<br>";       function adder($operand_1, $operand_2)       {          return $operand_1 + $operand_2;       }     ?>   </body> </html>

You can see what this application looks like in Figure 13.4.

image from book
Figure 13.4: The adder.php application

Returning multiple values from a function

Here’s something you might not expect: You can return multiple values from a function in PHP. For example, you might have a function, returner, that returns six different colors: red, green, yellow, and so on. How could you handle all six return values?

You can handle them with the PHP list function, which lets you work with a data construct called a list in PHP. Here’s how you would accept all six return values from the returner function, assigning them to variables $first, $second, and so on:

 <html>   <head>     <title>       Returning multiple values from functions     </title>   </head>   <body>     <h1>       Returning multiple values from functions     </h1>     <?       list($first, $second, $third, $fourth, $fifth,         $sixth) = returner();         .         .         .     ?>   </body> </html>

then you could echo the multiple returned values this way:

 <html>   <head>     <title>       Returning multiple values from functions     </title>   </head>    <body>     <h1>       Returning multiple values from functions     </h1>     <?       list($first, $second, $third, $fourth, $fifth,         $sixth) = returner();       echo "\$first: $first<BR>";       echo "\$second: $second<BR>";       echo "\$third: $third<BR>";       echo "\$fourth: $fourth<BR>";       echo "\$fifth: $fifth<BR>";       echo "\$sixth: $sixth<BR>";         .         .         .     ?>   </body> </html>

How do you return multiple values from a function in PHP? One way is to simply place them into an array and to return that array, which looks like this:

 <html>   <head>     <title>       Returning multiple values from functions     </title>   </head>   <body>     <h1>       Returning multiple values from functions     </h1>     <?       list($first, $second, $third, $fourth, $fifth,         $sixth) = returner();       echo "\$first: $first<BR>";       echo "\$second: $second<BR>";       echo "\$third: $third<BR>";       echo "\$fourth: $fourth<BR>";       echo "\$fifth: $fifth<BR>";       echo "\$sixth: $sixth<BR>";       function returner()       {         $array = array("Red", "Green", "Yellow", "Blue",           "Orange", "Magenta");         return $array;       }     ?>   </body> </html>

You can see the results of this application, multipleReturns.php, in Figure 13.5.

image from book
Figure 13.5: The multipleReturns.php application

Now it’s time to turn to one of the most powerful parts of working with PHP: handling HTML controls.



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

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