一個例子簡要說明include和require的區別

先編輯command.php文件php

echo 'hello'.PHP_EOL;

而後編輯console.php文件bash

for($i=1;$i<=3;++$i){
	require 'command1.php';
}

本來想要包含並執行這個echo,沒想到寫錯了文件名,若是是require,會報出這樣的錯誤:ui

Warning: require(command1.php): failed to open stream: No such file or directory in console.php on line 4

Fatal error: require(): Failed opening required 'command1.php' (include_path='.') in console.php on line 4
PHP Warning:  require(command1.php): failed to open stream: No such file or directory in console.php on line 4
PHP Fatal error:  require(): Failed opening required 'command1.php' (include_path='.') in console.php on line 4

若是把require改成include設計

for($i=1;$i<=3;++$i){
	include 'command1.php';
}

會報出這樣的錯誤:blog

Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4

Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4

Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4

Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4

Warning: include(command1.php): failed to open stream: No such file or directory in console.php on line 4

Warning: include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4
PHP Warning:  include(command1.php): failed to open stream: No such file or directory in console.php on line 4
PHP Warning:  include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4
PHP Warning:  include(command1.php): failed to open stream: No such file or directory in console.php on line 4
PHP Warning:  include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4
PHP Warning:  include(command1.php): failed to open stream: No such file or directory in console.php on line 4
PHP Warning:  include(): Failed opening 'command1.php' for inclusion (include_path='.') in console.php on line 4

若是使用require_once或者include_once,只要包含路徑正確,那麼循環只執行一次。io

總結:console

使用require,若是文件沒有包含成功,就會報出一個fatal error,整個程序就停止了。class

使用include,若是文件沒有包含成功,就會報出一個普通的warning,以後的代碼仍會執行。require

若是你的Web程序使用了MVC這種對文件包含強依賴的設計方法,請使用require_once。stream

相關文章
相關標籤/搜索