PHP File Inclusion

There are two functions which can be used to included one PHP file into another PHP file.

  • include()
  • require()

Code ReusabilityBy the help of include and require statement, we can reuse code in many PHP scripts.

include()

The include statement includes and evaluates the specified file.

file1.php
<?php 
  $color = 'Yellow';
  $fruit = 'Mango';
?>

file2.php
<?php 
  echo "$fruit is $color color"; //  is color
  include 'file1.php';
  echo "$fruit is $color color"; //  Mango is Yellow color
?>

require()

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

var1.php
<?php 
  $color = 'Red';
  $fruit = 'Apple';
?>

var2.php
<?php 
  echo "$fruit is $color color"; //  is color
  require 'var1.php';
  echo "$fruit is $color color"; //  Apple is Red color
?>