php之文件载入include, include_once,require,require_once

这篇博客介绍了PHP中四种文件载入方法:include, include_once, require, require_once。内容包括它们的区别和使用场景。include在文件载入失败时会继续执行,而require会导致程序停止;include_once和require_once会在已载入时不重复加载,确保文件只被载入一次。文章详细讨论了文件路径的处理,包括相对路径、绝对路径和仅文件名的使用。" 7492714,46905,Windows 2008挂载NFS服务器教程,"['服务器', '网络', 'NFS', 'Windows 2008', 'CentOS']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

包含并运行指定文件,可以载入php或html文件
① include “文件路径”;
② include_once “文件路径”;
③ require “文件路径”;
④ require_once “文件路径”;
使用语法上4个语句都差不多。

1.文件路径

1.1 相对路径

 include "./page.php"//当前目录page.php 文件
 include "../page.html";//上一级目录page.html文件
 include "../../page.php";//上两级目录的page.php 文件

1.2 绝对路径

include "c:\mypro\page.php";//此写法不推荐
//另外两种写法
//①根据魔术常量 _DIR_ 写绝对路径
include _DIR_.'\page.php';

//②根据预定义常量 $_SERVER['DOCUMENT_ROOT']写绝对路径
$root = $_SERVER['DOCUMENT_ROOT'].'\mypro\page.php';

1.3 只给文件名

//不推荐,这样系统会按照一定规则自动寻找
include 'page.php';

2.区别

①include 载入文件失败时 提示错误继续执行后续代码
②require 载入文件失败时 提示错误停止执行后续代码,require 一般用在后续的代码依赖加载的文件
③include_once 跟include类似,另外在载入文件时,先判断是否有加载过,如果有则不加载,反之则加载
④require_once 跟require类似,另外在载入文件时,先判断是否有加载过,如果有则不加载,反之则加载

3.使用

<?php

header("content-type:text/html;charset=utf-8");

echo "我是主页开始。。。<br>";

include "./page1.php";//加载page1.php 1次

include "./page1.php";//加载page1.php 2次


include_once "./page1.php";//之前已加载过,此处不再加载

include "no_exist.php";//加载一个不存在的文件

echo "我是主页结束。。。<br>";

page1.php

<!DOCTYPE html>
<html>
 <head>
 <meta  charset="utf-8">
 <title> page1.php </title>
 </head>
 <body>
<table border="1">
    <tr>
        <td>11</td>
        <td>12</td>
    </tr>
    <tr>
        <td>21</td>
        <td>22</td>
    </tr>
</table>
<?php 
 echo "我是page1.php  AAA <br>";

 echo "我是page1.php BBBB <br>";

?>

 </body>
</html>

这里写图片描述

将上面代码修改下:

<?php

header("content-type:text/html;charset=utf-8");

echo "我是主页开始。。。<br>";

include "./page1.php";//加载page1.php 1次

include "./page1.php";//加载page1.php 2次


include_once "./page1.php";//之前已加载过,此处不再加载
//改为 require
require "no_exist.php";//加载一个不存在的文件
echo "我是主页结束。。。<br>";

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值