四種語句
PHP中有四個加載文件的語句:include、require、include_once、require_once。
基本語法
require:require函數(shù)一般放在PHP腳本的最前面,PHP執(zhí)行前就會先讀入require指定引入的文件,包含并嘗試執(zhí)行引入的腳本文件。require的工作方式是提高PHP的執(zhí)行效率,當(dāng)它在同一個網(wǎng)頁中解釋過一次后,第二次便不會解釋。但同樣的,正因?yàn)樗粫貜?fù)解釋引入文件,所以當(dāng)PHP中使用循環(huán)或條件語句來引入文件時,需要用到include。
include:可以放在PHP腳本的任意位置,一般放在流程控制的處理部分中。當(dāng)PHP腳本執(zhí)行到include指定引入的文件時,才將它包含并嘗試執(zhí)行。這種方式可以把程序執(zhí)行時的流程進(jìn)行簡單化。當(dāng)?shù)诙斡龅较嗤募r,PHP還是會重新解釋一次,include相對于require的執(zhí)行效率下降很多,同時在引入文件中包含用戶自定義函數(shù)時,PHP在解釋過程中會發(fā)生函數(shù)重復(fù)定義問題。
require_once / include_once:分別與require / include作用相同,不同的是他們在執(zhí)行到時會先檢查目標(biāo)內(nèi)容是不是在之前已經(jīng)導(dǎo)入過,如果導(dǎo)入過了,那么便不會再次重復(fù)引入其同樣的內(nèi)容。
相互區(qū)別
include和require:
include有返回值,而require沒有返回值。
include在加載文件失敗時,會生成一個警告(E_WARNING),在錯誤發(fā)生后腳本繼續(xù)執(zhí)行。所以include用在希望繼續(xù)執(zhí)行并向用戶輸出結(jié)果時。
//test1.php
?php
include './tsest.php';
echo 'this is test1';
?>
//test2.php
?php
echo 'this is test2\n';
function test() {
echo 'this is test\n';
}
?>
//結(jié)果:
this is test1
require在加載失敗時會生成一個致命錯誤(E_COMPILE_ERROR),在錯誤發(fā)生后腳本停止執(zhí)行。一般用在后續(xù)代碼依賴于載入的文件的時候。
//test1.php
?php
require './tsest.php';
echo 'this is test1';
?>
//test2.php
?php
echo 'this is test2\n';
function test() {
echo 'this is test\n';
}
?>
結(jié)果:
include和include_once:
include載入的文件不會判斷是否重復(fù),只要有include語句,就會載入一次(即使可能出現(xiàn)重復(fù)載入)。而include_once載入文件時會有內(nèi)部判斷機(jī)制判斷前面代碼是否已經(jīng)載入過。這里需要注意的是include_once是根據(jù)前面有無引入相同路徑的文件為判斷的,而不是根據(jù)文件中的內(nèi)容(即兩個待引入的文件內(nèi)容相同,使用include_once還是會引入兩個)。
//test1.php
?php
include './test2.php';
echo 'this is test1';
include './test2.php';
?>
//test2.php
?php
echo 'this is test2';
?>
//結(jié)果:
this is test2this is test1this is test2
//test1.php
?php
include './test2.php';
echo 'this is test1';
include_once './test2.php';
?>
//test2.php
?php
echo 'this is test2';
?>
//結(jié)果:
this is test2this is test1
//test1.php
?php
include_once './test2.php';
echo 'this is test1';
include './test2.php';
?>
//test2.php
?php
echo 'this is test2';
?>
//結(jié)果:
this is test2this is test1this is test2
//test1.php
?php
include_once './test2.php';
echo 'this is test1';
include_once './test2.php';
?>
//test2.php
?php
echo 'this is test2';
?>
//結(jié)果:
this is test2this is test1
require和require_once:同include和include_once的區(qū)別相同。
以上就是本次介紹的全部知識點(diǎn)內(nèi)容,感謝大家對腳本之家的支持。
您可能感興趣的文章:- 使用SMB共享來繞過php遠(yuǎn)程文件包含的限制執(zhí)行RFI的利用
- php文件包含目錄配置open_basedir的使用與性能詳解
- PHP中你應(yīng)該知道的require()文件包含的正確用法
- php 偽造本地文件包含漏洞的代碼
- PHP 網(wǎng)絡(luò)開發(fā)詳解之遠(yuǎn)程文件包含漏洞