If you do Web site development on any scale, you'll recognize the importance of reusable code snippets, whether it's blocks of HTML or PHP. For example, you'll change a footer containing your copyright information at least once a year, and if you have 1,000 pages (or even 10), it's a pain to have to do it all manually.
With PHP, you have a few different functions that help you to reuse code. The function you use depends on what you're reusing.
The main functions are:
* include() and include_once()
* require() and require_once()
include() function includes and evaluates the given file. For example:
Any code in the included file will be executed with a variable scope equal to that point at which the
include() occurred in the parent code. You can include static files on your server or target files on another server, using a combination of
include_once() function does the same thing as the
include() function, only it will check to see if the code from a file has already been included in the current script. If the code has already been included, the function will not include it again.
require() function replaces itself with the contents of the given file. This replacement happens when the PHP engine is compiling your code, and not at the time it's executing it, unlike
include(), which is evaluated first. The
require() function should be used for more static elements, leaving
include() for the dynamic elements. Like
require_once() function checks to see if the given code has been inserted already and will not insert the code again, should it already exist.
I tend to use the require function for things such as copyrights, static text, and other elements that contain no variables or that rely on other scripts executing in order to realize their content. For example:
[a lot of content]
// insert copyright
On the other hand, I often use
include() to pull in a library of functions or some such, at the outset of my script:
// get my function library
// do PHP things with my functions ?>
[a lot of content]
The next logical question would be, "Where do the included or required files come from?" The short answer is, "Anywhere on your system." However, if these are just code snippets, which sometimes contain important information such as database connectivity functions with exact usernames or passwords, then obviously you won't want them sitting in your document root for all the world to see.
You can put included or required files anywhere on your system, as long as the user under which PHP runs (www, nobody, whatever) has read access to those files. You can also give them any file extension that you want, or none at all.
require() to externalize those elements of your Web site that are omnipresent as well as subject to change will make your architecture much easier to deal with when you have to do updates.