include() 或 require() 函數,您可以在伺服器執行 php教程 檔案之前在該檔案中插入一個檔案的內容。除了它們處理錯誤的方式不同之外,這兩個函數在其他方面都是相同的。include() 函數會產生一個警告(但是指令碼會繼續執行),而 require() 函數會產生一個致命錯誤(fatal error)(在錯誤發生後指令碼會停止執行)。
<html>
<body>
<?php include("header.php"); ?>
<h1>welcome to my home page</h1>
<p>some text</p>
</body>
</html>
三個檔案,"default.php"、"about.php" 以及 "contact.php" 都引用了 "menu.php" 檔案。這是 "default.php" 中的代碼:
<?php include("menu.php"); ?>
<h1>welcome to my home page</h1>
<p>some text</p>
</body>
</html>
require() 函數
require() 函數與 include() 相同,不同的是它對錯誤的處理方式。
include() 函數會產生一個警告(但是指令碼會繼續執行),而 require() 函數會產生一個致命錯誤(fatal error)(在錯誤發生後指令碼會停止執行)。
如果在您通過 include() 引用檔案時發生了錯誤,會得到類似下面這樣的錯誤訊息:
php 代碼:
<html>
<body>
<?php
include("wrongfile.php");
echo "hello world!";
?>
</body>
</html>錯誤訊息:
warning: include(wrongfile.php) [function.include]:
failed to open stream:
no such file or directory in c:homewebsitetest.php on line 5
warning: include() [function.include]:
failed opening 'wrongfile.php' for inclusion
(include_path='.;c:php5pear')
in c:homewebsitetest.php on line 5
hello world!