Home Logo
Show Full Menu
Hide Full Menu
 

Include

Created: 09/10/10 Views: 1131 myFave Image


In this tutorial we will learn the include statement
The include statement is very useful and simple statement to use, it allows you to include another file into your current PHP file using the URL of the desired file.
This come extremely handy when we start the MySQL tutorials, but it can still be useful in usual PHP scripting. It almost works as if the contents of the desired file has been copied and then pasted into the PHP document where the include statement is written.
Along with include, there are also, include_once, require and require_once. These statements are very similar. The difference between include and require is that if the file cannot be found in a require statement, a fatal error will occur. The _once functions meant that if that file has already been included into the document, then it will not include it again.
I personally always seem to be using include_once, this is because I don't require a fatal error and I only really ever need the file to be included just the one time.

To write an these statements
  • include "Desired file";
  • include_once "Desired file";
  • require "Desired file";
  • require_once "Desired file";
You may sometimes see the quotation marks wrapped with brackets, this is also another correct way of writing these statements.

Here is a simple example of an include_once Statement
    newDoc.php
  • <?php
  • $colorA = "Orange";
  • $colorB = "Blue";
  • ?>

    Current Document
  1. <?php
  2. include_once "newDoc.php";

  3. print $colorB;
  4. ?>

    Result
  • Blue
The desired document, newDoc.php, has been included on line 2 which will include the 2 variables into the current document. A variable is then called and printed on line 4. If this include statement was after the variable was called, then the variable would have no value.

Copy and try for yourself!
    welcomeDoc.php
  • <?php
  • print "Hey!!
    ";
  • ?>

    Current Document
  1. <?php
  2. include_once "welcomeDoc.php";
  3. print "How are you?";
  4. ?>

    Result
  • Hey!!
  • How are you?


A little information about the directory for files.
    Here is our folder/file structure
  • www
  • index.php
  • about.php
  • Scripts
  • login.php
  • Extras
  • game.php
  • Include about.php in index.php | "about.php"
  • Include login.php in index.php | "scripts/login.php"
  • Include login.php in game.php | "../scripts/login.php"


back to: The Basics of PHP

There are no comments