Including Other Files
One of the most basic operations in PHP is including one script in another, thereby sharing functionality. This is done by using the include
keyword, specifying the filename you want to include.
For example, consider the following file, foo.php:
<?php
print "Starting foo\n";
include 'bar.php';
print "Finishing foo\n";
?>And also the file bar.php:
<?php
print "In bar\n";
?>PHP would load the file bar.php, read in its contents, then put it into foo.php in place of the include 'bar.php' line. Therefore, foo.php would look like this:
<?php
print "Starting foo\n";
print "In bar\n";
print "Finishing foo\n";
?>If you were wondering why it only writes in the In bar line and not the opening and closing tags, it is because PHP drops out of PHP mode whenever it includes another file, then reenters PHP mode as soon as it comes back from the file. Therefore, foo.php, once merged with bar.php, will actually look like this:
<?php
print "Starting foo\n";
?>
<?php
print "In bar\n";
?>
<?php
print "Finishing foo\n";
?>PHP includes a file only if the include line is actually executed. Therefore, the following code would never include bar.php:
<?php
if (53 > 99) {
include 'bar.php';
}
?>If you attempt to include a file that does not exist, PHP will generate a warning message. If your script absolutely needs a particular file, PHP also has the require keyword, which, if called on a file that does not exist, will halt script execution with a fatal error. Any file you include in ...