Using Library Files


After you have created a function that does something useful, you will probably want to use it again in other scripts. Rather than copy the function definition into each script that needs to use it, you can use a library file so that your function needs to be stored and maintained in only one place.

Before you go any further, you should create a library file called tax.php that contains both the add_tax and add_tax_rate functions but no other PHP code.

Using Library Files A library file needs to enclose its PHP code inside <?php tags just like a regular script; otherwise, the contents will be displayed as HTML when they are included in a script.


Including Library Files

To incorporate an external library file into another script, you use the include keyword. The following includes tax.php so that add_tax can be called in that script:

 include "tax.php"; $price = 95; echo "Price before tax: $price <br>"; echo "Price after tax: "; echo add_tax($price); 

Theinclude path Setting By default, include searches only the current directory and a few system locations for files to be included. If you want to include files from another location, you can use a path to the file.

You can extend the include path to include other locations without a path being required by changing the value of the include_path setting. Refer to Lesson 23, "PHP," for more information.


You can use the include_once keyword if you want to make sure that a library file is loaded only once. If a script attempts to define the same function a second time, an error will result. Using include_once helps to avoid this, particularly when files are being included from other library files. It is often useful to have a library file that includes several other files, each containing a few functions, rather than one huge library file.

Require The require and require_once instructions work in a similar way to include and include_once but have subtly different behavior. In the event of an error, include generates a warning, but the script carries on running as best it can. A failure from a require statement causes the script to exit immediately.




    Sams Teach Yourself PHP in 10 Minutes
    Sams Teach Yourself PHP in 10 Minutes
    ISBN: 0672327627
    EAN: 2147483647
    Year: 2005
    Pages: 151
    Authors: Chris Newman

    Similar book on Amazon

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