Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected T_VARIABLE error

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!

like image 777
neezer Avatar asked Nov 07 '09 20:11

neezer


1 Answers

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'];
    }
}
like image 155
Konrad Rudolph Avatar answered Oct 20 '22 13:10

Konrad Rudolph