Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

include

Inclusion, often represented by the include keyword and more rarely by require, is the process to read an external file, and evaluate with the current application for execution. It may define new structures, and execute code.

Inclusion relies on four language structures: include, require, include_once, require_once.

Inclusion is often only used in autoload() functions: the code is included class per class, upon request. Besides the include 'vendor/autoload.php';, there might be another inclusion for functions and global constant, which must be included manually.

Inclusion runs easily into the already defined error: this happens when the same file is included twice, and it defines a structure, such as function, constant, class, etc. At the second inclusion, the structure is already defined, and cannot be included again. This is why there is the include_once command, which skips the inclusion if it already happened. This error was later reduced by using autoload, which is only called when a class, interface, trait or enumeration is used.

vars.php
<?php

    $color = 'green';
    $fruit = 'apple';

?>

test.php
<?php

    echo "A $color $fruit"; // A
    
    include 'vars.php';
    
    echo "A $color $fruit"; // A green apple

?>

Documentation

See Also