在PHP类中使用XML

时间:2012-03-14 09:36:44

标签: php

  

可能重复:
  declare property as object?
  Why don't PHP attributes allow functions?

我试图通过在XML文档中存储连接字符串来复制.NET的web.config启发的想法。


但问题是我每次尝试在我的类中加载我的XML文件时都会遇到错误,该文件将处理数据库连接。

例如我有这个XML标记:
connections.xml

<?xml version="1.0" encoding="UTF-8" ?>
<connections>
    <connection name="MyConnection" 
                connectionstring="mysql:host=localhost;dbname=MyDatabase" 
                username="username" 
                password="password" />
</connections>


以及将处理它的PHP类。
Connection.php

<?php
    class Connection {
        // I keep getting errors here
        protected $xml = simplexml_load_file("connections.xml");

        // rest of my code here...
    }
?>


如果它有帮助,这里是抛出的错误消息。

Parse error: syntax error, 
             unexpected '(', expecting ',' or ';' in <path>\Connection.php on line 3

任何帮助将不胜感激,谢谢。 :)

1 个答案:

答案 0 :(得分:0)

您不能使用常量以外的任何内容初始化属性。也就是说,你可以这样做:

protected $xml = "constant";

这个:

protected $xml = something_a_function_returns();

所以你需要将代码移动到构造函数中:

class Connection {
    protected $xml;

    public function __construct() {
        $this->xml = simplexml_load_file("connections.xml");
    }
}