If you've used C before, you're probably already familiar with the "include" directive that appears near the beginning of every C program. PHP supports two functions which have a similar job to do - the include() function and the require() function. Take a look at a simple example: Now, if you try to access this page as it, you'll get a bunch of error messages warning you about missing files. So you need to create the files "gun.php4", "car.php4" and "watch.php4": [gun.php4] [car.php4] [watch.php4] And this time, when you access the primary page, PHP should automatically include the specified files, read the variables $gun, $watch and $car from them, and display them on the page. A quick note on the difference between the include() and require() functions - the require() function is always replaced by the contents of the file it points to, and therefore cannot be used in a conditional statement ["if this is true, require that file"] since the file will be read in regardless. However, the include() function allows you to optionally include or exclude files on the basis of a conditional test. Also, a require()d file cannot return values to the main PHP script, while an included file can. An important point to be noted is that when a file is require()d or include()d, the PHP parser leaves "PHP mode" and goes back to regular "HTML mode". Therefore, all PHP code within the included external files needs to be enclosed within regular PHP <?...?> tags. A very useful and practical application of the include() function is to use it to include a standard footer or copyright notice across all the pages of your Web site, like this: where "footer.html" contains <font size=-1 face=Arial>This material copyright Melonfire, 2000. All rights reserved.</font> Now, this footer will appear on each and every page that contains the include() statement above - and, if you need to change the message, you only need to edit the single file named "footer.html"! And that's about it for this week. We've shown you the basic building blocks of PHP - its variables and operators - and next time, we'll be using those fundamental concepts to demonstrate PHP's powerful form processing capabilities. Don't miss it!
blog comments powered by Disqus |