Home > php教程 > php手册 > body text

php include()函数测试分析

WBOY
Release: 2016-06-13 09:55:20
Original
758 people have browsed it

include_path 下寻找,然后是当前运行脚本所在目录相对的 include_path 下寻找。例如 include_path 是 . ,当前工作目录是 /www/ ,脚本中要 include 一个 include/a.php教程  并且在该文件中有一句 include "b.php" ,则寻找 b.php  的顺序先是 /www/ ,然后是 /www/include/ 。如果文件名以 ./  或者 ../  开始,则只在当前工作目录相对的 include_path 下寻找。

所以如下所示的文件结构

----a.php

----include/b.php

----include/c.php

 其中a.php

include 'include/b.php';

?>

-----------------------

b.php

include 'c.php';

include 'include/c.php';

?>

--------------------------

c.php

echo 'c.php';

?>

--------------------------

都能正确运行,说明b.php中两种不同包含路径都是可行的,根据include寻找包含文件的方式都能找到c.php。

但是最好的方式还是使用绝对路径,如果使用了绝对路径,php内核就直接通过路径去载入文件而不用去include path逐个搜索文件,增加了代码执行效率

define('root_path',dirname(__file__));

include root_path.'/c.php';

?>


结论:

显然include 后面路径的格式和php的include path 对程序性能都是存在影响的,include 性能从慢到快的排序是

include 'a.php'

在代码中,使用绝对路径include文件是最好的选择,因为这样php内核就直接通过路径去载入文件而不用去include path逐个搜索文件。

所以我们最好在项目的公用文件中定义一个项目根目录绝对路径的常量,然后所有的include的路径前都带上这个常量,这样项目中所有的include使用的都是绝对路径,既提高程序性能,也减少了相对路径带来的烦恼。

参考代码(来自emlog):

define('emlog_root', dirname(__file__));

include emlog_root . '/config.php';

如果你的项目中已经大量使用include 'test.php'  这样格式的相对路径且不好大量修改,那么请尽量减少php include path中的路径以提高一定的include性能。因为include path中的路径越少,php搜索文件的时间也越少。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!