include与require的区别及变量作用域
include()
include() 功能为引入并执行指定的目标文件。
关于 require() 的说明同样适用于本文档内容,这两种结构在处理逻辑上几乎完全一致,主要区别在于对错误的响应机制:include() 在遇到文件缺失时会生成一条警告信息,但脚本流程不会中断;而 require() 则会触发致命错误(Fatal Error),导致页面处理立即终止。因此,若希望在文件丢失时强制停止程序运行,应选用 require()。同时,请确保已正确配置 include_path 参数。
当文件被引入时,其内部代码将继承引入语句所在行的变量作用域。这意味着,从引入点开始,调用文件中在该行可访问的所有变量,在被引入的文件中均可正常使用。
例子12-3. 基本的 include() 例子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
?>若 include 语句位于调用文件的某个函数内部,则被引入文件中的所有代码将表现得如同是在该函数体内定义的一样,从而严格遵循该函数的局部变量作用域规则。
例子12-4. 函数中的包括<?php 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
?>文件被引入时,语法解析器会在目标文件的起始位置退出 PHP 模式并切换至 HTML 模式,直到文件末尾再恢复 PHP 模式。因此,目标文件中任何需要作为 PHP 代码执行的片段,都必须包裹在有效的 PHP 开始和结束标记内。
若在 PHP 配置中激活了“URL fopen wrappers”(默认开启状态),可以通过 URL(经由 HTTP 协议)而非本地路径来指定要引入的文件。如果目标服务器将该文件解析为 PHP 代码,则可以利用 HTTP GET 请求字符串向被引入文件传递变量。需注意的是,这与直接引入文件并继承父级变量空间有所不同:此时脚本实际上已在远程服务器上执行,本地脚本仅引入了其输出结果。
警告Windows 版本的 PHP 目前不支持该函数的远程文件访问功能,即使 allow_url_fopen 选项已被激活。
例子12-5. 通过HTTP 进行的include()<?php /* 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.
?>详细信息请参考使用远程文件章节,以及 fopen() 和 file() 函数说明。
由于 include() 和 require() 属于特殊的语言结构,在条件语句中使用时必须将其置于代码块(花括号)内。
例子12-6. include() 与条件语句组<?php // 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;
}
?>处理返回值:
可以在被引入的文件中使用 return() 语句来终止该文件的执行流程,并将控制权交还给调用它的脚本。同时,也可以从被引入的文件中返回具体的值。include 调用的返回值可以像普通函数一样被捕获和使用。
注: 在 PHP 3 版本中,除非是在函数内部调用,否则被引入文件中不能出现 return 语句。在此情况下,return() 的作用对象是该函数而非整个文件。
例子12-7. include() 和return() 语句return.php
<?php $var = 'PHP';
return $var;
?>noreturn.php
<?php $var = 'PHP';
?>testreturns.php
<?php $foo = include 'return.php';
echo $foo; // prints 'PHP'
$bar = include 'noreturn.php';
echo $bar; // prints 1
?>$bar 的值为 1 是因为 include 成功执行了。请注意上述示例中的差异:第一个例子在被引入文件中使用了 return(),而第二个没有。其他将文件“引入”到变量的方法还包括使用 fopen()、file() 或将 include() 与输出控制函数结合使用。