0

我正在尝试从 xml 读取凭据并使用 php 初始化为私有变量。

<?xml version="1.0" encoding="ISO-8859-1"?>
<config>
    <host>localhost</host>
    <username>Jani</username>
    <password>1234r</password>
</config>

我正在使用以下类和构造函数来初始化变量。

<?php

class Admin {

    public $host = "";
    private $username;
    private $password;
    private $table;
    private $crendentials = array();

    public function __construct() {

    $xml = simplexml_load_file("config.xml");

    foreach ($this->crendentials as $key => $value) {
        if ($key == $this->host) {
            $this->host = $value;
        } elseif ($key == $this->username) {
            $this->username = $value;
        } elseif ($key == $this->password) {
            $this->password = $value;
        }
    }


    foreach ($xml->children() as $child) {
        $this->crendentials[$child->getName()] = $child;
    }
}

public function getHost() {
    print_r($this->crendentials);
    echo $this->host;
    echo $this->username;
    echo $this->password;
}

}

$obj = new Admin;
$obj->getHost();
?>

它不是初始化变量。除此以外,还有没有加载凭据的好方法?我正在创建一个 cms。我做了一些研究,比如使用 ini 文件。但我认为 xml 是最简单的。

4

1 回答 1

0

它不是初始化变量。

我看到两个问题:

  • $this->crendentials是一个空数组。所以你的第一个foreach永远不会运行。
  • 从上面和内容来看$xml->children(),第二个foreach可能什么都不做。

除此以外,还有没有加载凭据的好方法?

撇开您从 XML 文件加载凭据不谈,我建议将两个foreach循环压缩为一个。只需循环遍历 XML 键并将它们分配给它们各自的类属性。也就是drop $this->crendentials

于 2012-12-31T23:21:09.410 回答