nclude()
The include() 语句包括并运行指定文件。
以下文档也适用于require()。这两种结构除了在如何处理失败之外完全一样。include() 产生一个警告而require() 则导致一个致命错误。换句话说,如果你想在遇到丢失文件时停止处理页面就用require()。include() 就不是这样,脚本会继续运行。同时也要确认设置了合适的include_path。
当一个文件被包括时,其中所包含的代码继承了include 所在行的变量范围。从该处开始,调用文件在该行处可用的任何变量在被调用的文件中也都可用。
例子12-3. 基本的 include() 例子
vars.php
复制代码 代码如下:
$color = 'green';
$fruit = 'apple';
?>
复制代码 代码如下:
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
复制代码 代码如下:
function foo()
{
global $color;
include 'vars.php';
echo "A $color $fruit";
}
/* vars.php is in the scope of foo() so *
* $fruit is NOT available outside of this *
* scope. $color is because we declared it *
* as global. */
foo(); // A green apple
echo "A $color $fruit"; // A green
?>
复制代码 代码如下:
/* This example assumes that www.example.com is configured to parse .php *
* files and not .txt files. Also, 'Works' here means that the variables *
* $foo and $bar are available within the included file. */
// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';
// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';
// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';
$foo = 1;
$bar = 2;
include 'file.txt'; // Works.
include 'file.php'; // Works.
?>
复制代码 代码如下:
// This is WRONG and will not work as desired.
if ($condition)
include $file;
else
include $other;
// This is CORRECT.
if ($condition) {
include $file;
} else {
include $other;
}
?>
复制代码 代码如下:
$var = 'PHP';
return $var;
?>
复制代码 代码如下:
$var = 'PHP';
?>
复制代码 代码如下:
$foo = include 'return.php';
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1
?>