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 ,脚本按预期工作。