The require_once() statement replaces
itself with the specified file, much like the C preprocessor's
#include works, and in that respect is
similar to the require() statement. The main
difference is that in an inclusion chain, the use of
require_once() will assure that the code is
added to your script only once, and avoid clashes with variable
values or function names that can happen.
For example, if you create the following 2 include files
utils.inc and foolib.inc
Example 11-2. utils.inc
<?php
define(PHPVERSION, floor(phpversion()));
echo "GLOBALS ARE NICE\n";
function goodTea() {
return "Oolong tea tastes good!";
}
?>
|
|
Example 11-3. foolib.inc
<?php
require ("utils.inc");
function showVar($var) {
if (PHPVERSION == 4) {
print_r($var);
} else {
var_dump($var);
}
}
// bunch of other functions ...
?>
|
|
And then you write a script
cause_error_require.php
Example 11-4. cause_error_require.php
<?php
require("foolib.inc");
/* the following will generate an error */
require("utils.inc");
$foo = array("1",array("complex","quaternion"));
echo "this is requiring utils.inc again which is also\n";
echo "required in foolib.inc\n";
echo "Running goodTea: ".goodTea()."\n";
echo "Printing foo: \n";
showVar($foo);
?>
|
|
When you try running the latter one, the resulting ouptut will be (using
PHP 4.01pl2):