Lesson 7 include and require


The include() statement includes and evaluates the specified file.

Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include() will finally check in the calling script's own directory and the current working directory before failing. The include() construct will emit a warning if it cannot find a file; this is different behavior from require(), which will emit a fatal error.

An example :-
vars.php
<?php

$color = 'green';
$fruit = 'apple';

?>

test.php
<?php

echo "A $color $fruit"; // A

include 'vars.php';

echo "A $color $fruit"; // A green apple

?>

require()

require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include() only emits a warning (E_WARNING) which allows the script to continue.


require_once()

The require_once() statement is identical to require() except PHP will check if the file has already been included, and if so, not include (require) it again.

include_once()

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include()statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.




Previous Post Next Post