require 的使用方法如 require("MyRequireFile.php"); 。這個函數通常放在 PHP 程式的最前面,PHP 程式在執行前,就會先讀入 require 所指定引入的檔案,使它變成 PHP 程式網頁的一部份。常用的函數,亦可以這個方法將它引入網頁中。
include()與require()的功能也基本相同(包含),但在用法上也有一些不同,include()是有條件包含函數,而require()則是無條件包含函數。例如在下面代碼中,如果變數$a為真,則將包含檔案a.php:
| 代碼如下 |
複製代碼 |
if($a){ include("a.php"); } |
include 使用方法如 include("MyIncludeFile.php"); 。這個函數一般是放在流程式控制制的處理部分中。PHP 程式網頁在讀到 include 的檔案時,才將它讀進來。這種方式,可以把程式執行時的流程簡單化。
而require()則和include()不同,不管$a取何值,下面的代碼將把檔案a.php包含進檔案裡:
| 代碼如下 |
複製代碼 |
if($a){ require("a.php"); } |
在錯誤處理方面,使用include語句,如果發生包含錯誤,程式將跳過include語句,雖然會顯示錯誤資訊但是程式還是會繼續執行!但requre卻會給你來個致命錯誤。
報錯
用例子來說話,寫兩個php檔案,名字為test1.php 和test2.php,注意相同的目錄中,不要存在一個名字是test999.php的檔案。
| 代碼如下 |
複製代碼 |
test.php <?PHP include (”test999.php”); echo “abc”; ?> test2.php <?PHP require (”test999.php”) echo “abc”; ?> |
瀏覽第一個檔案,因為沒有找到test999.php檔案,我們看到了報錯資訊,同時,報錯資訊的下邊顯示了abc,你看到的可能是類似下邊的情況:
Warning: include(test1aaa.php) [function.include]: failed to open stream: No such file or directory in D:WebSitetest.php on line 2
Warning: include() [function.include]: Failed opening ‘test1aaa.php’ for inclusion (include_path=’.;C:php5pear’) in D:WebSitetest.php on line 2
abc
瀏覽第二個檔案,因為沒有找到test999.php檔案,我們看到了報錯資訊,但是,報錯資訊的下邊沒有顯示abc,你看到的可能是類似下邊的情況:
Warning: require(test1aaa.php) [function.require]: failed to open stream: No such file or directory in D:WebSitetest.php on line 2
Fatal error: require() [function.require]: Failed opening required ‘test1aaa.php’ (include_path=’.;C:php5pear’) in D:WebSitetest.php on line 2