TemplateDirectory=tempdir
这是同
INI 文件相同的文件格式,但我自己编写了辅助工具。为此,我创建了自己的
Configuration 类,如下所示。
清单
7. text1.php
<
?php
class Configuration
{
ivate $configFile = ‘config.txt’;
private $items = array();
function __construct() { $this->parse(); }
function __get($id) { return $this->items[ $id ]; }
function parse()
{
$fh = fopen( $this->configFile, ‘r’ );
while( $l = fgets( $fh ) )
{
if ( preg_match( ‘/^#/’, $l ) == false )
{
preg_match( ‘/^(.*?)=(.*?)$/’, $l, $found );
$this->items[ $found[1] ] = $found[2];
}
}
fclose( $fh );
}
}
$c = new Configuration();
echo( $c->TemplateDirectory.”\n” );
?>
该代码首先创建了一个
Configuration 对象。该构造函数接下来读取 config.txt 并用解析过的
文件内容来设置局部变量
$items。
该脚本随后寻找
TemplateDirectory,这并没有在对象中直接定义。因此,使用设置成
‘TemplateDirectory’ 的 $id 来调用神奇的 __get 方法,__get 方法针对该键返回 $items 数组中
的值。
这个
__get 方法特定于 PHP V5 环境,所以此脚本必须在 PHP V5 下运行。实际上,本文中
所有的脚本都需要在
PHP V5 下运行。
当在命令行运行此脚本时,能看到下列结果:
% php text1.php
tempdir
%
一切都在预料之中,该对象读取
config.txt 文件,然后为 TemplateDirectory 配置项获得正确
的值。
但对于设置一个配置值,应该怎么做呢?在此类中建立一个新方法及一些新的测试代码,
就能够得到这个功能,如下所示。