PHP require和include有什么区别? [英] What is the difference between PHP require and include?
问题描述
我知道PHP的基本用法要求,要求一次,包含一次和包含一次.但是我对何时使用它们感到困惑.
I know the basic usage of PHP require, require once, include and include once. But I am confused about when I should use them.
示例:我有3个文件,例如:settings.php,database.php和index.php.
Example: I have 3 files, eg: settings.php, database.php, and index.php.
在database.php文件中,我写道:
In database.php file, i wrote:
require_once 'settings.php';
然后在index.php中,我写道:
and then in index.php, i wrote:
require_once 'settings.php';
require_once 'database.php';
所以我两次加载settings.php,这样可以吗?使用这些功能有什么提示吗?
so I load settings.php two times, is this okay? Any tips using these functions?
推荐答案
-
include
包含一个文件,如果找不到该文件,则会引发警告.include
includes a file and throws a warning if the file was not found.require
包含一个文件,如果找不到该文件,则会引发致命错误.require
includes a file and throws a fatal error if the file was not found.include_once
和require_once
做同样的事情,但只有(如果尚未加载文件).include_once
andrequire_once
do the same thing, but only if the file was not already loaded.但是,对
_once
函数之一的需求通常表示设计不良.您应该以明确定义在什么位置包含内容的方式来构建脚本.However, the need for one of the
_once
functions is usually a sign of bad design. You should build your scripts in a way that clearly defines what gets included where.选择一个位置供
settings.php
收录-可能是index.php
.无需在database.php
中另外添加它.Choose one place for
settings.php
to get included - probablyindex.php
. There should be no need to additionally include it indatabase.php
.这篇关于PHP require和include有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!