PHP include/require

Description

With include statement we can import reusable code and reuse it.

Syntax

Including other PHP files is done by include keyword.

include 'fileName.php';

or

require 'fileName.php';

Example

For example, consider the following file, foo.php:


<?php/*from  w  ww . java 2 s  .  com*/
        print "Starting foo";
        include 'bar.php';
        print "Finishing foo";
?>

And also the file bar.php:


<?php
       print "In bar";
?>

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//from  www. j a v  a 2s . c o  m
       print "Starting foo";
       print "In bar";
       print "Finishing foo";
?>

PHP includes a file if the include line is actually executed.


<?php/*from   ww w . j  a  v  a 2  s . c  o  m*/
       if (3 > 9) {
         include 'bar.php';//never include bar.php
       }
?>

require

Including a non-existing file will generate a warning message.

PHP has the require keyword, which will halt script execution if called on a non-existing file.

We usually put common functions, object definitions, and layout code into a file and then use include to reuse them.

For example, to reuse header on every page, we can start each of your pages with this:

include 'header.php';

include_once() and require_once()

include_once() and require_once() operate in the same way as include and require, respectively.

They will only include a file once. Include_once and require_once share the same list of already-included files.

When including or requiring a file, PHP first checks the directory in which the script is running, then it looks in its include path. The include path is defined in your php.ini file using the include_path directive.

The get_included_files() and get_required_files() functions tell the names of the included files.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition