例子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 ?
如果“URL fopen wrappers”在PHP 中被激活(默认配置),可以用URL(通过HTTP)而不是本地文件来指定要被包括的文件。如果目标服务器将目标文件作为PHP 代码解释,则可以用适用于HTTP GET 的URL 请求字符串来向被包括的文件传递变量。严格的说这和包括一个文件并继承父文件的变量空间并不是一回事;该脚本文件实际上已经在远程服务器上运行了,而本地 脚本则包括了其结果。
警告 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
// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the // local filesystem. include 'file.php?foo=1
// Works. include 'http://www.example.com/file.php?foo=1
$foo = 1; $bar = 2; include 'file.txt'; // Works. include 'file.php'; // Works. ?
例子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; } ?