Page 187 - Beginning PHP 5.3
P. 187

Chapter 7: Functions
                           When the PHP engine encounters the  return  statement, it immediately exits the function and returns
                           value  back to the code that called the function, which can then use the value as required.

                            The following example script shows how to define and use a function that returns a value:

                               < !DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
                               “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd” >
                               < html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en” >
                                < head >
                                  < title > Normal and bold text < /title >
                                  < link rel=”stylesheet” type=”text/css” href=”common.css” / >
                                < /head >
                                < body >
                                  < h1 > Normal and bold text < /h1 >
                               < ?php

                             function makeBold( $text ) {
                              return “ < b > $text < /b > ”;
                             }
                             $normalText = “This is normal text.”;
                             $boldText = makeBold( “This is bold text.” );
                             echo “ < p > $normalText < /p > ”;
                             echo “ < p > $boldText < /p > ”;
                              >
                             ?


                                < /body >
                             < /html >
                           This script defines a function,  makeBold() , that accepts a string argument and returns the string
                          enclosed by HTML    < b > ... < /b >   (bold) tags. It then creates a variable,  $normalText , containing an
                         unformatted string of text. Then it calls the   makeBold()  function, passing it some text to format, and
                          stores the return value from   makeBold()  in another variable,  $boldText . Finally, the script outputs
                         both   $normalText  and  $boldText  to the browser.

                            You can see the result in Figure  7 - 3 .

















                                     Figure 7-3


                                                                                                         149





                                                                                                      9/21/09   9:00:53 AM
          c07.indd   149
          c07.indd   149                                                                              9/21/09   9:00:53 AM
   182   183   184   185   186   187   188   189   190   191   192