PHP中include與require的用法區別

在PHP變成中,include()與require()的功能相同,include(include_once) 與 require(require_once)都是把把包含的文件代碼讀入到指定位置來,但是二者再用法上有區別:(include()是有條件包含函數,而require()則是無條件包含函數

1, 使用方式不同

(1) require 的使用方法如 require("requireFile.php"); 。這個函式通常放在 PHP 程式的最前面,PHP 程式在執行前,就會先讀入 require 所指定引入的檔案,使它變成 PHP 程式網頁的一部份。常用的函式,亦可以這個方法將它引入網頁中。引入是無條件的,發生在程序執行前,不管條件是否成立都要導入(可能不執行)。
(2) include 使用方法如 include("includeFile.php"); 。這個函式一般是放在流程控制的處理區段中。PHP 程式網頁在讀到 include 的檔案時,纔將它讀進來。這種方式,可以把程式執行時的流程簡單化。引入是有條件的,發生在程序執行時,只有條件成立時才導入(可以簡化編譯生成的代碼)。


例如在下面的一個例子中,如果變量$somgthing爲真,則將包含文件somefile:
if($something){
include("somefile");
}
但不管$something取何值,下面的代碼將把文件somefile包含進文件裏:
if($something){
require("somefile");
}
下面的這個有趣的例子充分說明了這兩個函數之間的不同。
$i = 1;
while ($i < 3) {
require("somefile.$i");
$i++;
}
在這段代碼中,每一次循環的時候,程序都將把同一個文件包含進去。很顯然這不是程序員的初衷,從代碼中我們可以看出這段代碼希望在每次循環時,將不同的文件包含進來。如果要完成這個功能,必須求助函數include():
$i = 1;
while ($i < 3) {
include("somefile.$i");
$i++;
}

2. 執行時報錯方式不同

include和require的區別:include引入文件的時候,如果碰到錯誤,會給出提示,並繼續運行下邊的代碼,require引入文件的時候,如果碰到錯誤,會給出提示,並停止運行下邊的代碼。例如下面例子:

寫兩個php文件,名字爲test1.php  和test2.php,注意相同的目錄中,不要存在一個名字是test3.php的文件。
test1.php
<?PHP
include  (”test3.php”);
echo  “abc”;
?>

test2.php
<?PHP
require (”test3.php”)
echo  “abc”;
?>

瀏覽第一個文件,因爲沒有找到test999.php文件,我們看到了報錯信息,同時,報錯信息的下邊顯示了abc,你看到的可能是類似下邊的情況:
Warning: include(test3.php) [function.include]: failed to open stream: No such file or directory in D:\WebSite\test.php on line 2

Warning: include() [function.include]: Failed opening ‘test3.php’ for inclusion (include_path=’.;C:\php5\pear’) in D:\WebSite\test.php on line 2
abc (
下面的被執行了

瀏覽第二個文件,因爲沒有找到test3.php文件,我們看到了報錯信息,但是,報錯信息的下邊沒有顯示abc,你看到的可能是類似下邊的情況:
Warning: require(test3.php) [function.require]: failed to open stream: No such file or directory in D:\WebSite\test2.php on line 2

Fatal error: require() [function.require]: Failed opening required ‘test3.php’ (include_path=’.;C:\php5\pear’) in D:\WebSite\test.php on line 2

下面的未被執行,直接結束

總之,include時執行時調用的,是一個過程行爲,有條件的,而require是一個預置行爲,無條件的。


發佈了52 篇原創文章 · 獲贊 37 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章