首頁 >後端開發 >php教程 >PHP中include和require的區別實例詳解

PHP中include和require的區別實例詳解

墨辰丷
墨辰丷原創
2018-05-22 16:13:171377瀏覽

網路上太多關於PHP中include與require區別。然而事實真的如此嗎,今天我們就透過一個具體的實例來簡單分析驗證下

先編輯command.php檔案

echo 'hello'.PHP_EOL;

然後編輯console.php檔

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

原本想要包含並執行這個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 &#39;command1.php&#39; (include_path=&#39;.&#39;) 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 &#39;command1.php&#39; (include_path=&#39;.&#39;) in console.php on line 4

如果把require改為include

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

##會報出這樣的錯誤:

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

Warning: include(): Failed opening &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) 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 &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) 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 &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) 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 &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) 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 &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) 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 &#39;command1.php&#39; for inclusion (include_path=&#39;.&#39;) 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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn