PHP包含文件-set_include_path

WBOY
Release: 2016-06-20 12:41:07
Original
922 people have browsed it

今天用的set_include_path和get_include_path,刚开始有些困惑,总结查询到的资料,得到如下结论:

1. get_include_path

该函数用于获取当前include_path 的值。

string get_include_path ( void )

例如windos下使用XAMPP输出:.;D:\xampp\php\PEAR

2. set_include_path


set_include_path()函数在脚本里动态地对PHP.ini中include_path修改。

include_path可以针对include和require的路径范围进行限定(预定义)。

(1)若没设置include_path值,则需要写完全的路径,但是这样这样会引入很多外部文件

例如:

<strong>include('123/test1.php'); include('123/test2.php');</strong>
Copy after login


(2)若设置include_path值可用下面代码代替。

set_include_path('123/'); include('test1.php'); include('test2.php');
Copy after login

因为,执行include或require时,会去include_path指定路径查找要引入文件,虽然不知道性能是否优化,但可以节省代码。当然,还有玄机!

(3)这个函数不仅可定义一个文件夹,还可定义很多文件夹。如下,写一个初始化函数:

function initialize(){ set_include_path(get_include_path().PATH_SEPARATOR . 'core/'); set_include_path(get_include_path().PATH_SEPARATOR . 'app/'); set_include_path(get_include_path().PATH_SEPARATOR . 'admin/'); set_include_path(get_include_path().PATH_SEPARATOR . 'lib/'); set_include_path(get_include_path().PATH_SEPARATOR . 'include/'); set_include_path(get_include_path().PATH_SEPARATOR.'data/'); set_include_path(get_include_path().PATH_SEPARATOR.'cache/');}
Copy after login

它的路径成了:

.;C:\php5\pear;core/;app/;admin/;lib/;include/;data/;cache/
Copy after login

前面的.;C:\php5\pear;是php.ini中include_path的默认值。按照这个思路,如果加载许多文件夹的话,就可以直接写文件名了。

同时设置多个include_path时可以用PHP常量PATH_SEPARATOR来分割。在类unix的系统中,PATH_SEPARATOR是 ":";在windows系统中,PATH_SEPARATOR的值是";";

示例:

set_include_path(implode(PATH_SEPARATOR, array(  realpath(APPLICATION_PATH . '/../lib'),  get_include_path(), )));
Copy after login



(4)当指定一个目录为include_path时,但是当lib目录下找不到所要求包含的文件,而在当前页面目录下正好存在这个名称的文件时,则转为包含当前目录下的该文件。

示例:

set_include_path('projectName/home/Action/lib');require('a.php');

(5)当指定了多个目录为 include_path ,而所要求包含的文件在这几个目录都有相同名称的文件存在时,php选择使用设定 include_path 时排位居前的目录下的文件。





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 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!