include has another feature, you can assign the return value of the script to a variable. So if you wanted to build up a webpage you can do this with includes.
PHP Code:
<?php
/**
* file: header.php
*/
$external = include('external.php');
return "<html><head><title>$title</title>$external</head><body>\n";
?>
<?php
/**
* file: external.php
*/
$output = '';
if($scripts && is_array($scripts)) {
foreach($scripts as $script) {
$output .= "<script type=\"text/javascript\" src=\"$script\"></script>\n";
}
}
if($styles && is_array($styles)) {
$output .= "<style type=\"text/css\">";
foreach($styles as $style) {
$output .= "@include $style;\n";
}
}
return $output;
?>
<?php
/**
* file: footer.php
*/
return "<div id=\"footer\">goodbye world</div></body></html>";
?>
<?php
/**
* file: index.php
*/
$scripts = array(
'script1.js',
'script2.js'
);
$styles = array(
'style1.css',
'style2.css'
);
$title = "include example";
$page = include('header.php');
$page .= 'hello world';
$page .= include('footer.php');
echo $page;
?>
This example allows the title, javascript files and stylesheets to be assigned to variables before the includes and then they are all put into a single string before printing them to browser.
There is also a function require, which generally performs better because the require function only looks at the code once it is used, whereas include looks at the code straight away. The other difference between the 2 is that require will raise a fatal error if the file is missing, whereas include will only raise a warning.
Both include and require have similar functions, include_once and require_once. They their names suggest, they will only be referenced once in the code, the best use is when you have modular code which has multiple dependencies, because then php won't try to redeclare your functions or classes.