PHP require VS include
php
在PHP 語言中如果你想插入額外的一段程式就會用到 require 跟 include 兩個函式。它們的功能相同,不同的是處理錯誤的方式。
require:
這個語法通常使用在程式檔案的一開頭,載入程式時會先讀取require引入的檔案,使其變成程式的一部分。以下是一段引入網頁CSS的範例:
require(“theme.css”);
include:
include功能跟require一樣,通常使用在程式中的流程敘述中,比如 「if … else」「while loop」「for loop」等。以下是一段引入其他 PHP 頁面的範例:
include(“function.php”);
require 跟 include的分別:
兩者的分別在當遇上錯誤時,require 會生成一個 (E_COMPILE_ERROR),並在錯誤發生後立即停止執行餘下程式。而include 則會生成一個 (E_WARNING),在錯誤發生後會繼續執行餘下的程式。
以一個網頁的代碼為例:
<html> <head><?php require("theme.css"); ?></head> <body> "Hello World!" </body> </html>
如果require出現了錯誤,你將不會看到 “Hello Word!” 等內容,因為程式會在出現錯誤時就停止。
<html> <head><?php include("function.php"); ?></head> <body> "Hello World!" </body> </html>
反之,如果include出現了錯誤你都可以看到 “Hello Word!” 等內容。
由於它們的特性,require比較適合引入靜態的內容例如 CSS,而include則適合引入動態的程式碼比如 PHP ﹑ INC等。