Control Structures


include

The include statement includes and evaluates the specified file.

Syntax Description
include filename; includes the specified file into current script
filename can be referenced by a variable
filename is case-sensitive
test.php
<?php
$var1 = 1;
$var2 = 2;
?>
init.php
<?php
$var1 = $var2 = 0;
echo $var1 + $var2;
include "test.php";  // includes test.php
echo $var1 + $var2;
?>
[result]  
03
  • Example of include within functions
    If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, they are declared to global variables if you want to use them in global scope.
test.php
<?php
$var1 = 1;
$var2 = 2;
?>
init.php
<?php
$var1 = $var2 = 0;
function func()
{
  global $var1;        // only $var1 is global
  include "test.php";  // includes test.php
  echo $var1 + $var2;
}
func();
echo $var1 + $var2;
?>
[result]  
31
  • Example of include with return
    If included file has no return argument, include returns 1 on success. On failure, it causes PHPoC error.
test1.php
<?php
// return $var
$var = 3;
return $var;
?>
test2.php
<?php
// no return
$var = 3;
return;
?>
init.php
<?php
$var1 = include "test1.php";
echo $var1;
$var2 = include "test2.php";
echo $var2;
?>
[result]  
31