Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page