網路上太多關於PHP中include與require區別。然而事實真的如此嗎,今天我們就透過一個具體的實例來簡單分析驗證下
先編輯command.php檔案
echo 'hello'.PHP_EOL;
然後編輯console.php檔
for($i=1;$i<=3;++$i){ require 'command1.php'; }
原本想要包含並執行這個echo,沒想到寫錯了檔名,如果是require,會報出這樣的錯誤:
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'; }##會報出這樣的錯誤:
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,只要包含路徑正確,那麼迴圈只會執行一次。 總結:使用require,如果檔案沒有包含成功,就會報出一個fatal error,整個程式就中止了。 使用include,如果檔案沒有包含成功,就會報出一個普通的warning,之後的程式碼仍會執行。 如果你的網路程式使用了MVC這種對檔案包含強依賴的設計方法,請使用require_once。 相關推薦:
以詳細講解php中require,include,use區分
關於PHP Include 檔案的解說###############PHP基礎學習之包含require,###include### ########### ##################
以上是PHP中include和require的區別實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!