PHP Programming/PHP Include Files

IncludesEdit

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 only throw a warning if there is a problem during the include process; require, however, will halt execution 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.

Include OnceEdit

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.

Last modified on 18 August 2010, at 23:41