您好,登錄后才能下訂單哦!
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,之后的代碼仍會執行。
如果你的Web程序使用了MVC這種對文件包含強依賴的設計方法,請使用require_once。
看完上述內容,你們掌握PHP中include與require有什么區別的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。