PHP 包含檔案

在本教程中,你將學習如何在 PHP 中包含和評估檔案。

將 PHP 檔案包含到另一個 PHP 檔案中

include()require() 語句是讓你在一個 PHP 檔案中中包含另外一個 PHP 檔案中的程式碼。包含檔案產生的結果與從指定檔案複製指令碼並貼上到呼叫它的位置的結果相同。

你通過包含檔案來工作可以節省大量時間 - 只需將程式碼塊儲存在單獨的檔案中,並使用 include()require() 語句將其包含在任何位置,而不是多次鍵入整個程式碼塊。一個典型的例子是在網站的所有頁面中包括頁首,頁尾和選單檔案。

include()require() 語句的基本語法如下:

include("path/to/filename"); -Or- include"path/to/filename";
require("path/to/filename"); -Or- require"path/to/filename"; 

提示:printecho 語句一樣,你可以在使用上面演示的 includerequire 語句時省略括號。

下面的示例將向你展示如何在網站的所有頁面中包含分別儲存在單獨的 header.phpfooter.phpmenu.php 檔案中的公共頁首,頁尾和選單程式碼。使用此技術,你可以通過僅對一個檔案進行更改來一次更新網站的所有頁面,這可以節省大量重複性工作。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Tutorial Republic</title>
</head>
<body>
<?php include "header.php"; ?>
<?php include "menu.php"; ?>
    <h1>Welcome to Our Website!</h1>
    <p>Here you will find lots of useful information.</p>
<?php include "footer.php"; ?>
</body>
</html>

includerequire 語句之間的區別

你可能會想,既然我們可以使用 include() 語句包含檔案,那麼我們為什麼需要 require() 呢。通常情況下, require() 語句的操作就像 include() 一樣。

唯一的區別是 - include() 語句,如果找不到要包含的檔案,只會生成一個 PHP 警告,它允許指令碼繼續執行,而 require() 語句將生成致命錯誤並停止執行指令碼。

<?php require "my_variables.php"; ?>
<?php require "my_functions.php"; ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><?php displayTitle($home_page); ?></title>
</head>
<body>
<?php include "header.php"; ?>
<?php include "menu.php"; ?>
    <h1>Welcome to Our Website!</h1>
    <p>Here you will find lots of useful information.</p>
<?php include "footer.php"; ?>
</body>
</html>

**提示:**如果你要包含庫檔案或包含執行應用程式所必需的功能和配置變數的檔案 (例如資料庫配置檔案) ,建議使用 require() 語句。

include_oncerequire_once 語句

如果你使用 include 或者 require 語句在程式碼中多次包含相同的檔案(通常是函式檔案) ,則可能會導致衝突。為了防止這種情況,PHP 提供 include_oncerequire_once 語句。這些語句的行為方式與 includerequire 語句相同,只有一個例外。

即使要求第二次包含該檔案, include_oncerequire_once 語句也只包括該檔案,即如果指定的檔案已經包含在先前的語句中,則該檔案不再包括在內。為了更好地理解它是如何工作的,讓我們看看一個例子。假設我們有一個 my_functions.php 檔案,程式碼如下:

<?php
function multiplySelf($var){
    $var *= $var; // multiply variable by itself
    echo $var;
}
?>

這是我們在其中包含’my_functions.php’檔案的 PHP 指令碼。

<?php
// Including file
require "my_functions.php";
// Calling the function
multiplySelf(2); // Output: 4
echo "<br>";
 
// Including file once again
require "my_functions.php";
// Calling the function
multiplySelf(5); // Doesn't execute
?>

當你執行上面的指令碼時,你將看到如下錯誤訊息: Fatal error: Cannot redeclare multiplySelf()。發生這種情況是因為’my_functions.php’被包含兩次,這意味著函式 multiplySelf() 被定義了兩次,這導致 PHP 停止指令碼執行併產生致命錯誤。現在重寫上面的例子 require_once

<?php
// Including file
require_once "my_functions.php";
// Calling the function
multiplySelf(2); // Output: 4
echo "<br>";
 
// Including file once again
require_once "my_functions.php";
// Calling the function
multiplySelf(5); // Output: 25
?>

正如你所看到的,通過使用 require_once 而不是 require ,指令碼按預期工作。