views:

213

answers:

2

Okay, I know this is a common enough question, but all the solutions I've found thus far have involved a missing semi-colon or curly brace, both of which I know is not the case for me.

I have a class that works FINE with this variable assignment:

session.php:

<?php

   class session {
     ... 
     var $host = 'localhost';
     ...
   }

?>

Great. But I want to have my database details in another file, so I did this:

db_creds.php:

<?php

   var $db_creds = array(
      'host' => 'localhost',
      ...
   );

?>

session.php

<?php

   include('db_creds.php');

   class session {
     ... 
     var $host = $db_creds['host'];
     ...
   }

?>

Which then gave me this error: Parse error: syntax error, unexpected T_VARIABLE in ../session.php on line 74, where line 74 is my var $host assignment.

I even tried doing this in session.php, just to be sure the problem wasn't in the include:

session.php

<?php

   # include('db_creds.php');

   class session {
     ...
     var $db_host = 'localhost';
     var $host = $db_host;
     ...
   }

?>

... but that just throws the same error as above.

Can anyone tell me what's happening here? I'm at my wits end!

+5  A: 

Variables are not allowed here, properties must be initialized by constants in PHP:

[…] this initialization must be a constant value

[Source: php.net manual]

Use the constructor to intialize the value properly:

class session {
    var $host;

    function __construct() {
        $this->host = $db_creds['host'];
    }
}
Konrad Rudolph
Ahh, got it. Still new to PHP classes and whatnot. Thanks! +1
neezer
+1  A: 

1-the first letter in a class name should be capital (class Session)

2- did you write a constructor

3- class properties are accessed with $this->property

Anas Toumeh