PHP Programming/PHP Include Files
Includes
[edit | edit source]There are two methods of including a file in PHP: include and require.
include "file.php";
require "file.php";
They both perform essentially the same function, but have one major difference: include will throw a warning if there is a problem in the include process (for example, if it could not find the file); require, however, will halt execution with a fatal error in this scenario. Therefore, a script's dependencies will often be called with require.
Prior to version 4.0.2, require also attempted to read a file, regardless of whether the code in that file was executed or not. This means that if a file did not exist, an error would be thrown even if it would never be interpreted. The following code:
<?php
if (false) {
require "some_nonexistent_file.php";
}
require "another_nonexistent_file.php";
would therefore fail on the first require in versions before 4.0.2, and the second in all other versions.
By default, the include path is .:/usr/share/php on Linux (meaning it searches for files in the current directory and in /usr/share/php) and .;c:\php\includes on Windows (meaning it searches in the current directory and in c:\php\includes. These can be modified in your php.ini configuration file.
include_once
[edit | edit source]Additionally, there exist many code libraries, class definitions, and variable declarations that you will want to separate into an include file, but that should only be called into the current script once. To ensure that these libraries are only included once, php includes the include_once() and require_once()functions.
Each time one of these functions is called, the php parser remembers which file it has called. If another include_once()or require_once attempts to load the same file, the parser will simply skip the command. It will produce no error or warning, it will simply act as though the command had executed successfully. This is because, in fact, it has.
IMPORTANT: If you include a file once with include_once() and then later using include(), the file will be included a second time. If a file is included using include_once() and a call to the same file is made by require_once(), it will not be included again. Include_once() and require_once() have the same 'memory,' as it were.