background image

PHP 中文件包含语句的函数的几个区别

  PHP 中有四个包含文件的函数:include(), include_once(), require()和 require_once()。弄清楚
他们的区别是学习

PHP 的基础之一,可以避免不少写代码过程中产生的不必要的麻烦。

  

include()

  

1. 调用方式:include(“/path/to/filename”)

  

2. 说明: include()语句将在它被调用的地方包含参数所指定的文件,其效果和将某个

文件的内容复制在

include()出现的地方一样。使用 include()时,括号可以忽略,如:include 

“/path/to/filename”。
  

3. 陷阱:通过 if…else…条件语句来判断是否 include 某个文件时有一个怪现象。如

  

<?php

  

if(expression)

  

include("/path/to/filename");

  

else

  

include("/path/to/anotherfilename");

  

?>

  上面这段代码运行时可能出错。为什么呢

?include()函数只是将文件内容复制到出现该

include()函数的地方,如果文件中包含多行 php 语句而没有使用{}组成代码快呢?那整个
if…else…的逻辑就乱了。所以,这段代码应该这样写:
  

<?php

  

if(expression){

  

include("/path/to/filename");

  

}

  

else{

  

include("/path/to/anotherfilename");

  

}

  

?>

  这样就可以确保所包含进来的文件在整个代码快中。
  

include_once()

  

1. 调用方式:include_once(“filename”)

  

2. 说明:顾名思义,只包含一次该文件。即,如果上下文中已经包含过了该文件,那么

就不再包含。
  

3. 陷阱:拥有和 include()函数一样陷阱。

  

require()

  

1. 调用方式:require(“filename”)

  

2. 说明:除了以下两点之外,功能跟 include()一样:(1)无论 require()出现在程序片段

的什么位置,它都能将文件包含进来。考虑如下程序:
  

<?php

  

if(false){

  

require("/path/to/filename");

  

}

  

else{

  

require("/path/to/anotherfilename");

  

}