例子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; } ?