> 文章列表 > php include_once

php include_once

php include_once

什么是 '.php include_once'

在编写PHP脚本时,可能会需要在一个文件中使用另一个文件的代码。这时可以使用include和require两个语句来实现,它们的主要区别是当文件不存在、路径不正确或者有语法错误时,include仅仅会产生警告而不终止程序继续执行,而require则会产生致命错误并停止程序的执行。

如果多次引入同一个文件,include和require的不断执行会增加服务器的负担,而导致性能瓶颈,这时可以使用include_once和require_once来避免重复载入文件,这两个语句的作用是:仅仅在第一次载入文件时起作用,再次载入时就被忽略。

PHP include_once VS include

在使用include语句时,如果当前文件中包含的引用文件有重复,重复的文件会产生错误提示,为了避免这种错误,可以使用include_once语句。

include_once语句可以防止文件被多次载入,而这样避免了由于重复载入而导致的错误提示,比如“cannot re-declare function”错误:


include_once语句和include语句的用法十分相似,两者都有同样的基本语法,但是实现的效果却有所不同。

PHP include_once VS require_once

In PHP, require_once statement is identical to include_once, except that it will cause a fatal error if the file cannot be included. For example, if we include a file that does not exist, an include statement would prompt a warning and continue executing whereas a require statement would shut down the script immediately.

Not only does require_once produce a fatal error if it fails to include the file, but it also prevents the file from ever getting included again for the duration of the script. This can be important in certain scenarios where the contents of the included file need only be displayed once or the content of the included file contains code that should not be executed twice.

For example, the following code would fail because the file is not present:


The require_once statement will make the script halt and print the following message:

Fatal error: require_once(): Failed opening required 'non_existent_file.php' (include_path='.;C:\php\pear') in C:\htdocs\test.php on line 2

'.php include_once' 的应用

'.php include_once'的应用是在PHP脚本中分离模块代码

PHP include语句可以在脚本中引用其他文件中的代码。这样可以分离脚本中的模块代码,使得代码结构变得更加清晰简洁。

include_once的应用:

在使用include语句时,如果当前文件中包含的引用文件有重复,重复的文件会产生错误提示。为了避免这种错误,可以使用include_once语句。例如,在一个服务端脚本中,可以编写下面的代码:


如何debug '.php include_once'语句的错误

使用include和include_once函数载入文件时,PHP中会检查是否设置了include_path变量,如果没有设置,系统会查找硬盘上指定的文件,如果文件不存在,则返回错误。

当PHP执行include和include_once函数载入文件时,如果路径不正确,也会返回错误。如果你要载入的文件中有错误,PHP解释器会输出有关这些错误的信息。

PHP错误信息常常有如下内容:

Warning: failed to open stream: No such file or directory in filename.php on line xx

Warning: include_once(): Failed opening 'filename.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in filename.php on line xx

Fatal error: Can't use method return value in write context in filename.php on line xx

PHP错误信息中,包含了可以用来解决问题的提示。例如:

Warning: failed to open stream: No such file or directory in filename.php on line xx

这个错误意味着检测到要载入的文件不存在。在这种情况下,需要确定被载入文件的路径映射是否正确。

Warning: include_once(): Failed opening 'filename.php' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in filename.php on line xx

这个错误提示表明,PHP在查找文件时找不到指定的目录。在这种情况下,需要重新检查路径映射是否正确。

Fatal error: Can't use method return value in write context in filename.php on line xx

这个错误提示表明,代码上下文导致PHP不能正常地解释你的代码行。在这种情况下,需要逐个排查代码并重新修复它们。