1.include()與require()的區別(同理可區分include_once()與require_once()) include(),require()語句包含並運行指定文件。 這兩種結構除了在如何處理失敗之外完全一樣。 include()產生一個警告而require()則導致一個致命錯誤。換句話說,如果想在遇到丟失文件時停止處理頁面就用 require()。include()就不是這樣,腳本會繼續運行 例1:include()產生一個Warning而require()則導致一個Fatal error。 zhanhailiang@linux-06bq:~> php -r "include('a.php');" Warning: include(a.php): failed to open stream: No such file or directory in Command line code on line 1 Warning: include(): Failed opening 'a.php' for inclusion (include_path='.:/usr/local/services/phplib/src:/usr/local/services/phplib/inc:/usr/local/services/php/lib/php') in Command line code on line 1 zhanhailiang@linux-06bq:~> php -r "require('a.php');" Warning: require(a.php): failed to open stream: No such file or directory in Command line code on line 1 Fatal error: require(): Failed opening required 'a.php' (include_path='.:/usr/local/services/phplib/src:/usr/local/services/phplib/inc:/usr/local/services/php/lib/php') in Command line code on line 1 2.include()與include_once()的區別(同理可區別require()與require_once()) include_once()語句在腳本執行期間包含並運行指定文件。此行為和include()語句類似,唯一區別是如果該文件中的代碼已經被包含了,則不會再次包含。如同此語句名字暗示的那樣,只會包含一次。 include_once()應該用於在腳本執行期間同一個文件有可能被包含超過一次的情況下,想確保它只被包含一次以避免函數重定義,變量重新賦值等問題。 返回值和include()相同。如果文件已被包含,本函數返回TRUE。 例1:include()會多次包含指定文件,而include_once()不會。 zhanhailiang@linux-06bq:~> cat a.php <?php echo '1'.PHP_EOL; zhanhailiang@linux-06bq:~> php -r "include('a.php');include('a.php');" 1 1 zhanhailiang@linux-06bq:~> php -r "include_once('a.php');include_once('a.php');" 1 www.2cto.com 例2:include_once()避免函數重定義。 zhanhailiang@linux-06bq:~> cat a.php <?php echo '1'.PHP_EOL; function test() {} zhanhailiang@linux-06bq:~> php -r "include('a.php');include('a.php');" 1 Fatal error: Cannot redeclare test() (previously declared in /home/zhanhailiang/a.php:4) in /home/zhanhailiang/a.php on line 4 zhanhailiang@linux-06bq:~> php -r "include_once('a.php');include_once('a.php');" 1