您的位置:首页 > 产品设计 > UI/UE

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

2016-04-05 21:26 621 查看
包含并运行指定文件,可以载入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>";


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: