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

實例比較PHP中include和require的區別

巴扎黑
發布: 2023-03-15 14:44:01
原創
1585 人瀏覽過

網路上太多關於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中include和require的區別的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板