0

Possible Duplicate:
declare property as object?
Why don't PHP attributes allow functions?

I'm trying to replicate the idea inspired by .NET's web.config by storing connection strings in an XML document.


but the problem is I keep getting an error everytime I try to load my XML file in the my class that would handle the database connectivity.

for example I have this XML markup:
connections.xml

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


and the PHP class that would handle it.
Connection.php

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

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


if it helps, here is the error message that is being thrown.

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

any help would be greatly appreciated, thanks. :)

Community
  • 1
  • 1
Drew
  • 888
  • 7
  • 12

1 Answers1

0

You cannot initialize a property with anything other than a constant. That is, you can do this:

protected $xml = "constant";

but not this:

protected $xml = something_a_function_returns();

So you need to move that code into the constructor:

class Connection {
    protected $xml;

    public function __construct() {
        $this->xml = simplexml_load_file("connections.xml");
    }
}
Jon
  • 428,835
  • 81
  • 738
  • 806
  • 1
    oh come on. thats a well known duplicate. dont answer it please. – Gordon Mar 14 '12 at 09:42
  • @Gordon: For such easy questions I find it's easier to just answer on the spot. When/if someone CVs, I usually see that and add a vote too. – Jon Mar 14 '12 at 09:59
  • @Jon That is short sighted though. See http://meta.stackexchange.com/questions/91180/is-it-my-responsibility-to-search-for-duplicates-vote-to-close-before-answerin/105231#105231 why. – Gordon Mar 14 '12 at 10:21
  • @Gordon: I understand and respect your opinion (and even partially agree). We disagree on how to come to grips with the fact that related q detection on SO is way off where it needs to be on a technical level; your proposal of fighting the issue with zealous perserverence towards the One True Answer is not practical enough for me, and my idea of "just give the customer a good answer since you can, next!" probably feels dirty to you. We both want to help people though (I could label your opinion "obsessive-compulsive" to go with my "short-sighted", but really both of those are unfair). – Jon Mar 14 '12 at 10:32
  • @Jon fair enough. I wouldnt call my opinion obsessive-compulsive though but rather disciplined ;) – Gordon Mar 14 '12 at 10:42