PHP - 获取和设置include_path
分类: PHP 2011-02-16 13:19 2818人阅读 评论(1) 收藏 举报
include_path是PHP中的一个环境变量,在php.ini中初始化设置,类似于JAVA的CLASSPATH和操作系统中的PATH。
例如:有如下一些文件, /www/index.php /www/includes/config.php /www/includes/functions.php /www/includes/PEAR/PEAR.php /www/includes/PEAR/DB.php /www/includes/PEAR/DB/mysql.php
如果没有设置include_path变量,index.php需要这样写:
[php] view plaincopyprint?
- <?php
- include_once ‘/www/includes/config.php‘;
- include_once ‘/www/includes/PEAR/DB.php‘;
- include_once ‘/www/includes/PEAR/DB/mysql.php‘;
- ?>
<?php
include_once ‘/www/includes/config.php‘;
include_once ‘/www/includes/PEAR/DB.php‘;
include_once ‘/www/includes/PEAR/DB/mysql.php‘;
?>
使用上面的引用方式,引用路径比较长,当引用目录位置改变时需要大量修改代码。使用include_path变量可以简化上述问题:
[php] view plaincopyprint?
- <?php
- set_include_path(/www/includes‘ . PATH_SEPARATOR . /www/includes/PEAR‘);
- include_once ‘config.php‘;
- include_once ‘DB.php‘;
- include_once ‘DB/mysql.php‘;
- ?>
<?php
set_include_path(/www/includes‘ . PATH_SEPARATOR . /www/includes/PEAR‘);
include_once ‘config.php‘;
include_once ‘DB.php‘;
include_once ‘DB/mysql.php‘;
?>
include_path是PHP的环境变量,因而可以在php.ini设置,每次请求时include_path都会被PHP用php.ini中的值初始化。也可以用代码的方式修改include_path值,不过,修改后结果在请求完毕后会自动丢弃,不会带到下一个请求。因此,每次请求时需要重新设置。
在代码中获取和设置include_path值有如下两种方式:
方式一:ini_get()和ini_set()方式,此种方式使用于所有PHP版本。
[php] view plaincopyprint?
- <?php
- $s = ini_get(‘include_path‘);
- ini_set($s . PATH_SEPARATOR . ‘/www/includes‘);
- ?>
<?php
$s = ini_get(‘include_path‘);
ini_set($s . PATH_SEPARATOR . ‘/www/includes‘);
?>
方式二:get_include_path()和set_include_path()方式,此种方式使用于PHP4.3以后的版本。
[php] view plaincopyprint?
- <?php
- $s = get_include_path();
- set_include_path($s . PATH_SEPARATOR . ‘/www/includes‘);
- ?>
<?php
$s = get_include_path();
set_include_path($s . PATH_SEPARATOR . ‘/www/includes‘);
?>