PHP parse_ini_file oop&深的 [英] php parse_ini_file oop & deep

查看:67
本文介绍了PHP parse_ini_file oop&深的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用[parse_ini_file] [1]之类的东西.

I would like to make use of somehting like [parse_ini_file][1].

比如说我有一个boot.ini文件,我将加载该文件以进行进一步的操作:

Lets say for instance I have a boot.ini file that I will load for further procedure:

    ;database connection settings
[database]
type        =   mysql;
host        =   localhost;
username    =   root;
password    =   "";
dbName      =   wit;

但是,我想用一种与php数组不同的方式来获取它:

However, I would like to have it in a different way as the php array would be:

$ini['database']['whatever']

因此,首先,我希望将boot.ini设置为以下结构:

So first of all I would like to have my boot.ini like this structure:

;database settings (comment same style)
db.host1.type = mysql;
db.host1.host = localhost;
db.host1.username = root;
db.host1.password = "";
db.host1.dbName = wit;

db.host2.type = mysql;
db.host2.host = otherHost;
db.host2.username = root;
db.host2.password = "";
db.host2.dbName = wit;

因此,当我现在访问文件时,我想以这种方式访问​​它:

So when I now access the file I would like to access it this way:

$ini['db']['host1']['whatever']

最重要的是,我想通过OOP进行操作,所以可以这样说: $ ini-> db-> host1->任何内容

And on top of that I would like to do it via OOP so lets say: $ini->db->host1->whatever

or `$ini->db->host1` 

将返回具有所有属性的数组,例如类型,主机,用户名,密码和dbName;

will return an array with all the attributes such as type, host, username, password and the dbName;

我非常感谢您的帮助.提前非常感谢您.

I appreciate anykind of help. Thank you very much in advance.

  [1]: http://uk2.php.net/manual/en/function.parse-ini-file.php

推荐答案

好,您需要对 parse_ini_file 进行后处理结果数组.

Well, you need to postprocess the parse_ini_file result array then.

$ini_array = parse_ini_file("bootstrap.ini");

$ini = new stdclass;
foreach ($ini_array as $key=>$value) {
    $c = $ini;
    foreach (explode(".", $key) as $key) {
        if (!isset($c->$key)) {
            $c->$key = new stdclass;
        }
        $prev = $c;
        $c = $c->$key;
    }
    $prev->$key = $value;
}

更新 Hackety-Hack.现在,使用额外的$prev再次取消设置上一个对象级别. (用于检测最后一个$ key的for循环会更好地工作.)

Update Hackety-Hack. Now using an extra $prev to unset the last object level again. (A for loop to detect the last $key would have worked better).

如果要使用数组语法对象语法,则将new stdclass替换为new ArrayObject(array(), 2);.

If you want to use the array syntax and the object syntax, then replace the new stdclass with new ArrayObject(array(), 2);.

这篇关于PHP parse_ini_file oop&深的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆