PHP include & require函数详解

首页 / PHP入门教程 / PHP include & require函数详解

PHP使无涯教程能够创建各种元素和函数,这些元素和函数在许多页面中多次使用。将这些函数编写成多个页面需要花费大量时间。因此,使用文件包含(file inclusion)的概念有助于在各种程序中包含文件,并节省了多次编写代码的工作。

PHP允许您包含文件,以便页面内容可以多次重复使用。当您要将相同的HTML或PHP代码应用于网站的多个页面时,包含文件非常有用。有两种方法可以在PHP中包含文件。

  1. include
  2. require

include和require作用相同,但加载失败时处理方式不同。

  • include   - 仅生成警告,即E_WARNING,并继续执行脚本。
  • require   - 会产生致命错误,即E_COMPILE_ERROR,并停止执行脚本。

PHP include

PHP include 用于根据给定路径包含文件。您可以使用文件的相对或绝对路径。

有两种语法可用于:

include 'filename ';
Or 
include ('filename');

例子

看一个简单的PHP include 示例。

file:menu.html

<a href="http://www.learnfk.com">Home</a> |   
<a href="http://www.learnfk.com/php-tutorial">PHP</a> |   
<a href="http://www.learnfk.com/java-tutorial">Java</a> |    
<a href="http://www.learnfk.com/html-tutorial">HTML</a>  

文件:include1.php

<?php include("menu.html"); ?>
<h1>这是主页</h1>

输出:

Home | 
PHP | 
Java |  
HTML

这是主页

PHP require

PHP require类似于include,它也用于包含文件。唯一的区别是,如果找不到文件,而没有包含文件,它将停止脚本的执行。

有两种可用于require的语法:

require 'filename';
Or 
require ('filename');

例子

看一个简单的PHP require示例。

file:menu.html

<a href="http://www.learnfk.com">Home</a> |   
<a href="http://www.learnfk.com/php-tutorial">PHP</a> |   
<a href="http://www.learnfk.com/java-tutorial">Java</a> |    
<a href="http://www.learnfk.com/html-tutorial">HTML</a>

file:require1.php

<?php require("menu.html"); ?>
<h1>这是主页</h1>

输出:

Home | 
PHP | 
Java |  
HTML

这是主页

include vs require

include和require都会加载文件。但是,如果文件丢失或包含失败,则 include 允许脚本继续运行,但是 require 会暂停脚本,从而产生致命的E_COMPILE_ERROR级别错误。

借助示例来了解不同之处:

include.php

<?php 
	//include welcome.php file 
	include("welcome.php");
	echo "The welcome file is included.";
?>

输出:

welcome.php 文件在无涯教程包含的同一目录中不可用。因此,它将产生有关该丢失文件的警告,并显示输出。

Warning: include(welcome.php): failed to open stream: No such file or directory in C:\xampp\htdocs\program\include.php on line 3

Warning: include(): Failed opening 'welcome.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\program\include.php on line 3
The welcome file is included.

require.php

<?php
	echo "HELLO";
	//require welcome.php file 
	require("welcome.php");
	echo "The welcome file is required.";
?>

输出:

如果是require(),则在同一目录中找不到文件( welcome.php )。如以下输出所示,require()会生成致命错误并停止脚本的执行。

HELLO
Warning: require(Welcome.php): failed to open stream: No such file or directory in C:\xampp\htdocs\program\include.php on line 3

Fatal error: require(): Failed opening required 'Welcome.php' (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\program\include.php on line 3

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

邱岳的产品手记 -〔邱岳〕

MySQL实战45讲 -〔林晓斌〕

Linux实战技能100讲 -〔尹会生〕

JavaScript核心原理解析 -〔周爱民〕

RPC实战与核心原理 -〔何小锋〕

正则表达式入门课 -〔涂伟忠〕

高楼的性能工程实战课 -〔高楼〕

技术面试官识人手册 -〔熊燚(四火)〕

反爬虫兵法演绎20讲 -〔DS Hunter〕

好记忆不如烂笔头。留下您的足迹吧 :)