PHP提供了以下文件包含方式:1. include 和 require:加载外部文件,如果文件不存在,前者会产生警告,后者会终止执行;2. include_once 和 require_once:与前者类似,但只包含文件一次;3. fopen() 和 fread():打开文件并读取内容;4. file_get_contents():读取文件内容并返回字符串;5. heredoc 和 nowdoc:定义多行字符串。

PHP 文件包含方式
PHP 提供了多种文件包含方式,用于将外部文件的内容加载到当前脚本中。
1. include 和 require
- include:如果文件不存在,会产生一个 E_WARNING 错误,且脚本继续执行。
- require:如果文件不存在,会产生一个 E_COMPILE_ERROR 错误,且脚本终止执行。
2. include_once 和 require_once
立即学习“PHP免费学习笔记(深入)”;
- include_once:和 include 类似,但只包含文件一次,即使它被多次包含。
- require_once:和 require 类似,但只包含文件一次,即使它被多次包含。
3. fopen() 和 fread()
- fopen():打开一个文件并返回一个文件指针。
- fread():从文件指针中读取内容。
4. file_get_contents()
- 读取整个文件的内容并返回一个字符串。
5. heredoc 和 nowdoc
- heredoc:使用 <<< 和一个标识符来定义一个多行字符串。
- nowdoc:使用 `` 和一个标识符来定义一个多行字符串,不解析变量或转义字符。
示例
要包含文件 example.php:
<code class="php"><?php
include "example.php"; // 使用 include
require "example.php"; // 使用 require
include_once "example.php"; // 使用 include_once
require_once "example.php"; // 使用 require_once
// 使用 fopen() 和 fread()
$file = fopen("example.php", "r");
$contents = fread($file, filesize("example.php"));
fclose($file);
// 使用 file_get_contents()
$contents = file_get_contents("example.php");
// 使用 heredoc
$contents = <<<EOF
<?php
// 内容 here
EOF;
// 使用 nowdoc
$contents = <<<'EOF'
<?php
// 内容 here
EOF;
?></code>











