set_include_path简叙


        在看框架源码中,相信不少都见过此函数吧。对于新手来说,不明其意,今天就简单说下此函数。


        set_include_path函数是为当前脚本设置include_path 运行时的配置选项的。这里引用下include_path官方的解释

include_path string
Specifies a list of directories where the require, include, fopen(), file(), readfile() and file_get_contents() functions look for files. The format is like the system's PATH environment variable: a list of directories separated with a colon in Unix or semicolon in Windows.

PHP considers each entry in the include path separately when looking for files to include. It will check the first path, and if it doesn't find it, check the next path, until it either locates the included file or returns with a warning or an error. You may modify or set your include path at runtime using set_include_path().

Example #1 Unix include_path
include_path=".:/php/includes"

Example #2 Windows include_path
include_path=".;c:\php\includes"

Using a . in the include path allows for relative includes as it means the current directory. However, it is more efficient to explicitly use include './file' than having PHP always check the current directory for every include.

        也就是设置此函数后,会对常用的include等函数产生影响。举个例子,在项目中要大量引用include目录的文件,那么可以把此目录放入include_path,以后直接引用里面的文件即可。

define('INCLUDE_PATH', APP_PATH . DIRECTORY_SEPARATOR . 'include');
set_include_path(INCLUDE_PATH);
include 'conn.php';

        如果设置多个目录呢

define('INCLUDE_PATH', APP_PATH . DIRECTORY_SEPARATOR . 'include');
define('FILE_PATH', APP_PATH . DIRECTORY_SEPARATOR . 'file');
#其中PATH_SEPARATOR在windows是'\',在linux是'/'
set_include_path(
    INCLUDE_PATH . PATH_SEPARATOR .
    FILE_PATH . PATH_SEPARATOR .
    get_include_path()
);
#其中PATH_SEPARATOR在windows是';',在linux是':'
echo get_include_path();
#显示 .:/var/app/include:/var/app/file
#其中.代表当前目录
#不过官方也说了,使用./filename比使用直接引入include_path更有效率


你可能感兴趣的:(set_include_path简叙)