Creating a Function


How do you create your own function? Here's how to do it formally:

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

What does all this mean? Let's take a look at an example. Say that all your web pages have a navigation bar with hyperlinks at the bottom. Instead of including all the code to send the needed HTML to the browser in each web page that features this bar, you could set up a function, which we'll call nav_bar, to do it for you:

 function nav_bar() {          .          .          . } 

The statements in this function will be executed when you call it, so here's where we add the echo statements to send the HTML for the navigation bar and its hyperlinks back to the browser ("&nbsp" inserts a space in HTML to separate the links):

 function nav_bar() {     echo "<hr>";     echo "<center>";     echo "<a href='home.html'>Home</a>&nbsp;&nbsp;&nbsp;";     echo "<a href='map.html'>Site Map</a>&nbsp;&nbsp;&nbsp;";     echo "<a href='help.html'>Help</a>";     echo "</center>"; } 

Now when you call this function, the navigation bar is displayed. Centralizing the code to display your navigation bar also helps because if you want to change it, you only have to change it once, in the nav_bar function. You can see how this function might be called in phpnavbar.php, Example 4-1.

Example 4-1. Calling a function, phpnavbar.php
 <HTML>         <HEAD>             <TITLE>Using functions to create a navigation bar</TITLE>         </HEAD>         <BODY>             <H1>Using functions to create a navigation bar</H1>         <?php              echo "<H3>Welcome to my web page!</H3>";              echo "<br>";              echo "How do you like it?";              echo "<br>";              echo "<br>";             nav_bar();             function nav_bar()             {                 echo "<hr>";                 echo "<center>";                 echo "<a href='home.html'>Home</a>&nbsp;&nbsp;&nbsp;";                 echo "<a href='map.html'>Site Map</a>&nbsp;&nbsp;&nbsp;";                 echo "<a href='help.html'>Help</a>";                 echo "</center>";             }         ?>     </BODY> </HTML> 

You can see the navigation bar displayed at the bottom of the web page in Figure 4-1. Now to create that navigation bar, all you must do is call this new function.

Figure 4-1. Using a function.


Here's something else to know about functionsthe code in them doesn't run until the function is called. This is different from the standard code in a script, which is run when the web page loads. Being able to run code when you want gives you more control.



    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