Include and require
At some point of time you'll need to split your PHP file into several files and organize them properly. There are two methods of inclusion PHP files into each other: include
and require
:
include 'library.php';
require 'algorithms.php';
Both of them include a given file into the caller script. The major difference between these two methods is that: if the given file isn't found then include
will generate a warning when require
will generate an error (non-recoverable). In other words, require
is a strict version of include
.
You can return a value from the included file:
function.php
$value = 'Hello!';
return $value;
main.php
$value = include 'function.php';
echo $value; # Prints "Hello"
However, that's not a good design. You should use functions for that instead. If you don't use return
statement in the included file then include
will return a boolean value which means if the inclusion was successful:
if(include 'library.php')
{
echo 'The script was successfully included';
}
else
{
echo 'File not found';
}
Notice that if the file wasn't found then E_WARNING
will be generated. You can suppress it with @
prefix:
if(!@include 'library.php')
{
include 'fallback.php';
}
You can use __DIR__
macro to include files relatively to the current script. Consider the following files structure:
/home/sam/blog/index.php
/home/sam/blog/chat/chat.php
index.php
require __DIR__ . '/chat/chat.php'; # Include a file relatively to the current script's location
There are also special versions of include
and require
— include_once
and require_once
. They work exactly like their regular versions with an exception that a given file is included only one. That's useful when you include different files, which include other different files, and you don't want to include the same shared files multiple times.
When designing a library or some other type of a shared code, it's best to use require_once
method unless you have a good reason to do otherwise. Each .php
file should include all files it depends on, so every file could work as a standalone piece of functionality.