在本教程中,我们将学习如何使用PHP include函数将脚本文件中的代码包含到另一个脚本文件中。
PHP include函数允许您创建模块化和可重用的代码。PHP提供了四个函数来帮助您将脚本文件组织成模块并在另一个脚本文件中重用它们。
这四个函数是include()、require()、include_once()和require_once()。
PHP include()函数将脚本文件中的代码包含在另一个脚本文件中。通过使用include()函数,我们可以将代码分解成多个脚本文件,例如header.php,footer.php, functions.php和index.php文件。
以下是相应文件的源代码:
functions.php
<?php
/**
* 显示网站的头部
* @param string $title 站点的标题
*/
function
display_header(
$title
){
?>
<!DOCTYPE html>
<html>
<head>
<title><?php
echo
?></title>
</head>
<body>
}
* 显示网站的页脚
* @param string $content
display_footer(
$content
<footer>
; ?>
</footer>
</body>
</html>
* 显示标题
* @param string $tag 标题标签 比如 h1, h2, ...
* @param string $content 标题内容
display_heading(
$tag
,
$valid_tags
=
array
(
'h1'
'h2'
'h3'
'h4'
'h5'
'h6'
);
if
(in_array(
))
sprintf(
"<%s>%s</%s>"
else
die
(sprintf(
"Invalid tag %s"
));
header.php
include
'functions.php'
;
'PHP包含文件演示'
footer.php
$copyright
= sprintf(
"Copyright %d © theitroad.com 保留所有权利"
date
"Y"
在header.php和footer.php文件中,我们都包含了functions.php文件,这样就可以使用display_header()和display_footer()函数。
PHP还提供了require()函数,它的工作原理与include()函数相同,只是略有不同。include()函数和require()函数的区别在于,如果找不到要包含的文件,include()函数会发出PHP警告,而require()函数会发出致命错误并终止脚本。
假设我们想要在index.php文件中使用header.php和footer.php文件,以及functions.php文件中的函数。让我们试着把它们都包含在index.php中,如下所示:
'header.php'
'这是主标题'
'footer.php'
如果您运行脚本index.php,将会报一个致命错误,说明您不能再次定义display_header()函数。下图说明了我们如何使用include()函数组织文件:
包含display_header()函数的functions.php文件被包含了3次,因此我们得到了一个致命错误。
为了克服这个问题,PHP提供了两个有用的函数,让您只include文件一次。
要只包含一个文件一次,可以使用include_once()或require_once()函数。include()函数和include_once()函数的区别在于,include_once()函数只包含一个文件一次。如果再次调用include_once()函数来包含相同的文件,则不会做任何事情。
所以我们可以使用include_once()函数修复我们的问题,如下所示:
include_once
'PHP包括文件演示'
index.php
PHP 包含路径提供了一种方便的方法来定位要包含的文件的位置。include_path指令包含PHP用于搜索要包含的文件的路径列表。每个路径由冒号(:)或分号(;)分隔,这取决于部署PHP的平台。
要获得当前的包含路径,可以使用get_include_path()函数,如下所示:
get_include_path();
要设置一个新的包含路径,可以使用set_include_path()函数,如下所示:
set_include_path(
'.;/www/itroad/lib'
在调用set_include_path()函数后,可以在代码中包含如下文件:
当脚本执行时,PHP将在与脚本文件相同的目录中查找functions.php文件。如果找不到functions.php文件,PHP将在我们之前设置的include_path目录中搜索该文件。
通过使用include_path,我们的代码将会变得更加整洁和可移植。
可以在控制流语句(如if-else)或switch语句中调用include()或include_once()函数,根据一定的条件来包含文件。下面的例子演示了如何在PHP中动态包含一个文件:
$section
= isset(
$_GET
[
'section'
]) ?
] :
'main'
==
'header'
'footer'
{
原文链接:https://codingdict.com/