PHP之include和require的區別

2021-09-01 03:49:29 字數 2049 閱讀 1095

php之include和require的區別

include引入檔案的時候,如果碰到錯誤,會給出提示,並繼續執行下邊的**

require引入檔案的時候,如果碰到錯誤,會給出提示,並停止執行下邊的**

用例子來說話,寫兩個php檔案,名字為test-include.php和test-require.php,

注意相同的目錄中,不要存在乙個名字是test-nothing.php的檔案。

test-include.php

<?php

include 'test-nothing.php';

echo'abc';

?>

test-require.php

<?php

require 'test-nothing.php';

echo'abc';

?>

瀏覽http://localhost/test-include.php,因為沒有找到test-nothing.php檔案,

我們看到了報錯資訊,同時,報錯資訊的下邊顯示了abc,你看到的可能是類似下邊的情況:

warning: include(test-nothing.php) [function.include]: failed to open stream: no such file or directory in d:\www\test-include.php on line 2

warning: include() [function.include]: failed opening 'test-nothing.php' for inclusion (include_path='.;c:\php5\pear') in d:\www\test-include.php on line 2

abc瀏覽http://localhost/test-require.php,因為沒有找到test-nothing.php檔案,我們看到了報錯資訊,

但是,報錯資訊的下邊沒有顯示abc,你看到的可能是類似下邊的情況:

warning: require(test-nothing.php) [function.require]: failed to open stream: no such file or directory in d:\www\test-require.php on line 2

fatal error: require() [function.require]: failed opening required 'test-nothing' (include_path='.;c:\php5\pear') in d:\www\test-require.php on line 2

2.條件引用

include()與require()的功能相同,用法上卻有一些不同,include()是有條件包含函式,而require()則是無條件包含函式,

例如下面例子,如果變數$somg為真,則將包含檔案somefile.php:

if($some)

但無論$some取何值,下面的**將把檔案somefile.php包含進檔案裡:

if($something)

下面的例子充分說明了這兩個函式之間的不同

$i = 1;

while ($i < 3)

可以從以上這段**中看出,每一次迴圈的時候,程式都將把同乙個檔案包含進去,

很顯然這不我們想要的,可以看出這段**希望在每次迴圈時,

將不同的檔案包含進來,如果要完成這個功能,只能使用函式include()

$i = 1;

while ($i < 3)

3.檔案引用方式

include()執行時需要引用的檔案每次都要進行讀取和評估,

require()執行時需要引用的檔案只處理一次(實際上執行時需要引用的檔案內容替換了require()語句)

可以看出若有包含這些指令之一的**和可能執行多次的**,則使用require()效率比較高,

若每次執行**時相讀取不同的檔案或者有通過一組檔案疊代的迴圈,就使用include(),

可以給想要包括的檔名設定變數,當引數為 include()時使用這個變數

php之include的使用

伺服器端包含 ssi 用於建立可在多個頁面重複使用的函式 頁首 頁尾或元素。php include 和 require 語句 在 php 中,您能夠在伺服器執行 php 檔案之前把該檔案插入另乙個 php 檔案中。include 和 require 語句用於在執行流中向其他檔案插入有用的的 incl...

PHP之include載入檔案

include include once require require once 都屬於語法結構,而非函式,在載入檔案錯誤與檔案重複上區別 include include 在php的include語法中,如果沒有給出路徑而只有檔名,則include有自己的尋找規則 在系統設定的include目錄中...

php中include和require的區別

引用檔案的方法有兩種 require 及 include。兩種方式提供不同的使用彈性。require 的使用方法如require myrequirefile.php 這個函式通常放在 php 程式的最前面,php 程式在執行前,就會先讀入 require 所指定引入的檔案,使它變成 php 程式網頁...