PHP中引入文件的方法有:include、require、include_once、require_once。
區(qū)別介紹:
include和require
include有返回值,而require沒有返回值。
include在加載文件失敗時(shí),會(huì)生成一個(gè)警告(E_WARNING),在錯(cuò)誤發(fā)生后腳本繼續(xù)執(zhí)行。所以include用在希望繼續(xù)執(zhí)行并向用戶輸出結(jié)果時(shí)。
//test1.php <?php include './tsest.php'; echo 'this is test1'; ?> //test2.php <?php echo 'this is test2n'; function test() { echo 'this is testn'; } ?> //結(jié)果: this is test1
require在加載失敗時(shí)會(huì)生成一個(gè)致命錯(cuò)誤(E_COMPILE_ERROR),在錯(cuò)誤發(fā)生后腳本停止執(zhí)行。一般用在后續(xù)代碼依賴于載入的文件的時(shí)候。
//test1.php <?php require './tsest.php'; echo 'this is test1'; ?> //test2.php <?php echo 'this is test2n'; function test() { echo 'this is testn'; } ?>
結(jié)果:
include和include_once
include載入的文件不會(huì)判斷是否重復(fù),只要有include語(yǔ)句,就會(huì)載入一次(即使可能出現(xiàn)重復(fù)載入)。而include_once載入文件時(shí)會(huì)有內(nèi)部判斷機(jī)制判斷前面代碼是否已經(jīng)載入過。
這里需要注意的是include_once是根據(jù)前面有無(wú)引入相同路徑的文件為判斷的,而不是根據(jù)文件中的內(nèi)容(即兩個(gè)待引入的文件內(nèi)容相同,使用include_once還是會(huì)引入兩個(gè))。
//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ū)別相同。