Using Include Files


As you know now, functions let you break up your code and reuse the same code over and over. However, there's another PHP mechanism that lets you break up and reuse your code as wellinclude files. An include file holds text that will be included in your script if you use the PHP include statement.

Here's an example. We'll define a few handy constants in an include file named constants.inc (PHP include files usually have the extension .inc, although you can use .php if you want to make it more difficult for the user to download your include files for security reasons), shown in Example 4-15. Note that this include file uses the <?php ?> syntax.

Example 4-15. An include file, constants.inc
 <?php     define("pi", 3.14159);     define("e", 2.71828); ?> 

To include constants.inc in your script, use the statement include("constants.inc");, as in phpincludes.php, Example 4-16, and put the include file in the same directory as the script file. After you've included the include file, you're free to make use of the constants defined in it.

Example 4-16. Using include files, phpincludes.php
 <HTML>     <HEAD><TITLE>Using include files</TITLE></HEAD>     <BODY>         <H1>Using include files</H1>         <?php             echo "Including constants.inc....<BR>";             include("constants.inc");             echo "Got this value for pi: ", pi, "<BR>";             echo "Got this value for e: ", e, "<BR>";         ?>     </BODY> </HTML> 

The results, including the constants' values, appear in Figure 4-15.

Figure 4-15. Using include files.


You can also put code in include files, such as functions you might use frequently; you can even store entire libraries of functions this way. You can see a function, included_function, in function.inc in Example 4-17.

Example 4-17. An include file with a function, function.inc
 <?php     function included_function() {         echo "Hello from the included function!<BR>";     } ?> 

We can call the included function in phpincludefunction.php, Example 4-18.

Example 4-18. Using include files to include a function, phpincludefunction.php
 <HTML>     <HEAD><TITLE>Using include files</TITLE></HEAD>     <BODY>         <H1>Using include files</H1>         <?php             echo "Including function.inc....<BR>";             include("function.inc");             included_function();        ?>     </BODY> </HTML> 

The results appear in Figure 4-16. Very cool.

Figure 4-16. Using include files to include code.




    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