包含到另外一个文件中?
使用PHP语言,可以使用include或require关键字来将公用的文件包含到另一个文件中。
include和require的区别在于:当被包含的文件不存在或包含发生错误时,include将只会产生警告,程序会继续执行;而require则会产生致命错误,之后的程序都将停止执行。
同时,可以使用include_once和require_once来确保被包含文件只被执行一次。
以下是个例子,将一个公用的header文件包含到一个index文件中:
// index.php
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
<?php include "header.php"; ?>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
// header.php
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
这个例子中,header.php文件中的内容将被包含到index.php文件头部中,共同构成HTML页面。可以看到,通过包含公用的文件,可以方便地实现代码的复用和管理。