require()

The require() statement replaces itself with the specified file, much like the C preprocessor's #include works.

An important note about how this works is that when a file is include()ed or require()ed, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes PHP mode again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.

require() is not actually a function in PHP; rather, it is a language construct. It is subject to some different rules than functions are. For instance, require() is not subject to any containing control structures. For another, it does not return any value; attempting to read a return value from a require() call results in a parse error.

Unlike include(), require() will always read in the target file, even if the line it's on never executes. If you want to conditionally include a file, use include(). The conditional statement won't affect the require(). However, if the line on which the require() occurs is not executed, neither will any of the code in the target file be executed.

Similarly, looping structures do not affect the behaviour of require(). Although the code contained in the target file is still subject to the loop, the require() itself happens only once.

This means that you can't put a require() statement inside of a loop structure and expect it to include the contents of a different file on each iteration. To do that, use an include() statement.

require( 'header.inc' );
      

Please note that both include() and require() actually pull the contents of the target file into the calling script file itself; they do not call the target via HTTP or anything like that. So any variable set in the scope in which the inclusion happens will be available within the included file automatically, since it has effectively become a part of the calling file.

require( "file.inc?varone=1&vartwo=2" ); /* Won't work. */

$varone = 1;
$vartwo = 2;
require( "file.inc" );  /* $varone and $vartwo will be available in file.inc */
	 

Don't be misled by the fact that you can require or include files via HTTP using the Remote files feature; the above holds true regardless.

In PHP3, it is possible to execute a return statement inside a require()ed file, as long as that statement occurs in the global scope of the require()ed file. It may not occur within any block (meaning inside braces ({}). In PHP4, however, this ability has been discontinued. If you need this functionality, see include().